How to Send Emails to Multiple Recipients Using Python\'s smtplib.sendmail()?

Mary-Kate Olsen
Release: 2024-10-26 05:28:02
Original
552 people have browsed it

How to Send Emails to Multiple Recipients Using Python's smtplib.sendmail()?

Sending Email to Multiple Recipients using Python smtplib

When attempting to utilize Python's smtplib.sendmail to email multiple recipients, users often encounter issues. Despite specifying multiple addresses in the email header, only the first recipient receives the message.

This arises from a disparity in formatting expectations between the email.Message module and the smtplib.sendmail() function. The email.Message module accepts comma-delimited email addresses in the header, while sendmail() requires a list of addresses.

To effectively send email to multiple recipients using smtplib.sendmail, follow these steps:

  1. Create an email message using the email.MIMEMultipart module.
  2. Set the header fields ("From", "To", "Cc") to include multiple email addresses, separated by commas.
  3. Set the "To" parameter in the sendmail() function to a list of recipient email addresses (obtainable by splitting the comma-separated header field).
  4. Set the "From" parameter to the sender's email address.
  5. Compose the email body using the email.MIMEText module. Attach the body to the email message.
  6. Configure a connection to your SMTP server and send the email using sendmail().

Example code to send an email to multiple recipients using smtplib.sendmail:

<code class="python">from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import smtplib

msg = MIMEMultipart()
msg["Subject"] = "Example"
msg["From"] = "sender@example.com"
msg["To"] = "recipient1@example.com,recipient2@example.com,recipient3@example.com"
msg["Cc"] = "cc1@example.com,cc2@example.com"
body = MIMEText("example email body")
msg.attach(body)
smtp = smtplib.SMTP("mailhost.example.com", 25)
smtp.sendmail(msg["From"], msg["To"].split(",") + msg["Cc"].split(","), msg.as_string())
smtp.quit()</code>
Copy after login

The above is the detailed content of How to Send Emails to Multiple Recipients Using Python\'s smtplib.sendmail()?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!