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:
<code class="python">msg = MIMEMultipart()</code>
<code class="python">msg["To"] = "[email protected],[email protected],[email protected]"</code>
<code class="python">to_addrs = msg["To"].split(",")</code>
<code class="python">smtp = smtplib.SMTP("mailhost.example.com", 25) smtp.sendmail(msg["From"], to_addrs + msg["Cc"].split(","), msg.as_string())</code>
<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 protected]' recipients = ['[email protected]', '[email 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!