Python (Scripting) - Send an email

by
Jeremy Canfield |
Updated: April 01 2024
| Python (Scripting) articles
Following is a simple example Python script that can be used to send an email using smtplib, MIMEMultipart and MIMEText.
#!/usr/bin/python3
import smtplib
from smtplib import SMTPException
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
host = 'mail.example.com'
port = 587
username = 'xmailserviceaccount'
password = 'itsasecret'
sender = "No Reply <no-reply@example.com>"
recipients = ["John Doe <john.doe@example.com>", "Jane Doe <jane.doe@example.com>"]
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = ", ".join(recipients)
msg['Subject'] = "Example Subject"
message = "Example <b>Message</b>"
msg.attach(MIMEText(message, 'html'))
try:
server = smtplib.SMTP(host, port)
server.ehlo()
server.starttls()
server.ehlo()
server.login(username, password)
server.sendmail(sender, recipients, msg.as_string())
server.quit()
except SMTPException as exception:
print f"sendmail raised the following exception: {exception}"
else:
print "Email successfully sent"
Did you find this article helpful?
If so, consider buying me a coffee over at