Explain Codes LogoExplain Codes Logo

How to send email to multiple recipients using python smtplib?

python
email
smtplib
python-library
Anton ShumikhinbyAnton Shumikhin·Aug 30, 2024
TLDR

To email multiple recipients in Python, smtplib is your ally. Kickstart an SMTP connection and play it cool with the sendmail method. Serve a list of email strings as recipients, like so:

import smtplib # Server connection info smtp_server = "smtp.example.com" port = 587 # Remember this number! username = "username" password = "password" # Email content subject = "Subject" body = "Message body" # Maybe throw a meme here message = f"Subject: {subject}\n\n{body}" # Recipients array - your fan club recipients = ["[email protected]", "[email protected]"] # Send the email with smtplib.SMTP(smtp_server, port) as server: server.starttls() # Get ready for some TLS action server.login(username, password) # Login - they should know you by now server.sendmail(username, recipients, message) # And spam away!

Switch smtp_server, port, username, and password with your super secret SMTP stuff, edit subject, body, and recipients to give your message a personal touch.

Crafting custom MIME types

Get fancy by crafting the email with MIME types for top notch content and formatting:

from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart msg = MIMEMultipart() # The MAIN event msg['From'] = '[email protected]' msg['To'] = ', '.join(recipients) # The VIP list msg['Subject'] = 'Your Subject Here' # The hook # Attach a text body body = MIMEText('Your main message here', 'plain') # The juice msg.attach(body) # And tada - convert to string full_message = msg.as_string() server.sendmail(msg['From'], recipients, full_message) # Shoot the message!

Notice, msg['To'] needs a comma-separated banquet for display ceremonies, while sendmail prefers a discrete recipient list for delivery duties.

Silent recipients: cc and bcc

Invite bystanders silently using Cc and Bcc headers. Tuck them into the recipients list as well:

cc = ['[email protected]', '[email protected]'] # The lurkers bcc = ['[email protected]', '[email protected]'] # The spies msg['Cc'] = ', '.join(cc) msg['Bcc'] = ', '.join(bcc) # Don't forget: INVITE ALL to the send party all_recipients = recipients + cc + bcc server.sendmail(msg['From'], all_recipients, full_message)

Dodging errors

try and except blocks brace for errors and server.set_debuglevel(1) affords verbosity for debugging. It's like having psychic powers.

Prioritizing security

Prize Transport Layer Security (TLS) for its ironclad grip on email content safety. Ensure you suit up with server.starttls(), because protection is cool.

Avoid blatant credential reveals. Use secret-keepers like environment variables or config files off-limits from source control:

import os username = os.getenv('EMAIL_USERNAME') # We keep it secret password = os.getenv('EMAIL_PASSWORD') # We keep it safe

And, don't forget to freshen up your dependencies to stay on top of security trends.

Test large scale

Put your code through the wringer with thorough tests: reckoning invalid emails, feisty SMTP connections, and rate limits. Block smtplib methods in unit tests to prevent the unintended emailpocalypse.

And be nice — external email services like SendGrid or Mailgun integrate with Python libraries, assisting with delivery reports, bounce management, and spam gods.