Home  >  Article  >  Backend Development  >  How to Send Emails to Multiple Recipients Using Python\'s smtplib Module?

How to Send Emails to Multiple Recipients Using Python\'s smtplib Module?

Susan Sarandon
Susan SarandonOriginal
2024-10-25 07:57:29133browse

How to Send Emails to Multiple Recipients Using Python's smtplib Module?

How to Send Email to Multiple Recipients with Python's smtplib

Sending an email to multiple recipients using the smtplib module requires a slight adjustment in the email header and the function parameters.

The issue arises when setting the "To" header in the email.Message module with multiple addresses. While the header should contain comma-delimited email addresses, the smtplib.sendmail() function expects a list of recipients.

To resolve this, the following steps are needed:

  1. Create an email message using email.Message.MIMEMultipart():
<code class="python">msg = MIMEMultipart()</code>
  1. Set the email header with comma-delimited email addresses:
<code class="python">msg["To"] = "[email&#160;protected],[email&#160;protected],[email&#160;protected]"</code>
  1. Create a list of recipients for the sendmail() function:
<code class="python">to_addrs = msg["To"].split(",")</code>
  1. Use the sendmail() function with the list of recipients:
<code class="python">smtp = smtplib.SMTP("mailhost.example.com", 25)
smtp.sendmail(msg["From"], to_addrs + msg["Cc"].split(","), msg.as_string())</code>
  1. Quit the SMTP session:
<code class="python">smtp.quit()</code>

This approach will send the email to all the recipients specified in the "To" and "Cc" headers. Alternatively, a simpler solution can be found using MIMEText(), as shown below:

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

s = smtplib.SMTP('smtp.uk.xensource.com')
s.set_debuglevel(1)
msg = MIMEText("""body""")
sender = '[email&#160;protected]'
recipients = ['[email&#160;protected]', '[email&#160;protected]']
msg['Subject'] = "subject line"
msg['From'] = sender
msg['To'] = ", ".join(recipients)
s.sendmail(sender, recipients, msg.as_string())</code>

This version sends an email to the specified recipients using a single SMTP connection.

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

Statement:
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