Categories
Python Answers

How to send email to multiple recipients using Python smtplib?

Spread the love

Sometimes, we want to send email to multiple recipients using Python smtplib.

In this article, we’ll look at how to send email to multiple recipients using Python smtplib.

How to send email to multiple recipients using Python smtplib?

To send email to multiple recipients using Python smtplib, we can use the sendmail method.

For instance, we write:

import smtplib
from email.mime.text import MIMEText

s = smtplib.SMTP('smtp.live.com')
s.set_debuglevel(1)
msg = MIMEText("""body""")
sender = 'me@example.com'
recipients = ['john.doe@example.com', 'john.smith@example.co.uk']
msg['Subject'] = "subject line"
msg['From'] = sender
msg['To'] = ", ".join(recipients)
s.sendmail(sender, recipients, msg.as_string())

We create the SMTP instance by using the SMTP server address as the argument.

Then we create the message with the MIMEText class.

Next, we set the subject of the message with:

msg['Subject'] = "subject line"

We set the sender email address with:

msg['From'] = sender

And we set the recipients’ emails with:

msg['To'] = ", ".join(recipients)

We combine the recipients into a string with join.

Finally, we send the email with:

s.sendmail(sender, recipients, msg.as_string())

Conclusion

To send email to multiple recipients using Python smtplib, we can use the sendmail method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

2 replies on “How to send email to multiple recipients using Python smtplib?”

Leave a Reply

Your email address will not be published. Required fields are marked *