How to send email using Python

Sending mail is done with Python's smtplib using an Simple Mail Transfer Protocol (SMTP) server. Python's smtplib module defines an SMTP client session object that can be used to send mail to any Internet machine with an SMTP or ESMTP listener daemon.

Email and MIME objects

Multipurpose Internet Mail Extensions (MIME) is an Internet standard that expand upon the limited capabilities of email, and in particular to allow documents (such as images, sound, and text) to be inserted in a message.

example
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText fromaddr = "youraddress@gmail.com" toaddr = "some other email address" msg = MIMEMultipart() msg['From'] = fromaddr msg['To'] = toaddr msg['Subject'] = "Test Subject" body = "Write your message here" msg.attach(MIMEText(body, 'plain')) server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() server.login(fromaddr, "your password") text = msg.as_string() server.sendmail(fromaddr, toaddr, text) server.quit()
SMTPAuthenticationError when sending mail using gmail

Sometimes when you send email using gmail address you can see some error message like this:

raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError.....

It is because Google blocks sign-in attempts from apps which do not use modern security standards (mentioned on their support page). You can however, turn on/off this safety feature by going to the link below:

Go to this link and select Turn On

https://www.google.com/settings/security/lesssecureapps

Moreover google block an ip when you try to send a email since a unusual location, so, you can unblock in the next link

https://support.google.com/accounts/answer/6009563

and clicked in

accounts.google.com/DisplayUnlockCaptcha .

Gmail SMTP Settings


gmail smtp settings

If you use Gmail with your work or school account, check with your administrator for the correct SMTP configuration.