"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Send Emails to Multiple Recipients Using Python\'s smtplib?

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

Published on 2024-11-08
Browse:639

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

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

Utilizing smtplib.sendmail to transmit emails to several recipients can be challenging. To successfully deliver messages to multiple addresses, follow these guidelines:

Set the Header with Comma-Delimited Email Addresses:

In the header of the email (msg["To"]), use a string of comma-separated email addresses instead of a single recipient address.

Utilize a List for sendmail to_addrs Parameter:

Rather than a string, the to_addrs argument of smtplib.sendmail() should be a list containing individual email addresses. These addresses can be obtained by splitting the comma-separated string in the header.

Consider the following code snippet as an illustration:

import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText

msg = MIMEMultipart()
msg["Subject"] = "Subject Line"
msg["From"] = "[email protected]"
msg["To"] = "[email protected], [email protected], [email protected]"
body = MIMEText("Body of the email")
msg.attach(body)

smtp = smtplib.SMTP("mailhost.example.com")
smtp.sendmail(msg["From"], msg["To"].split(","), msg.as_string())
smtp.quit()

Alternatively, you can use the following approach:

import smtplib
from email.mime.text import MIMEText

s = smtplib.SMTP('smtp.uk.xensource.com')
msg = MIMEText("""**Body of the email""")
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())
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3