Python email
Sending emails in python uses at least two libraries.
- an email message object (headers, body, attachments) is built
- a library is used to send the message
email.message.Message
This object builds the body of an email message, the header, and any attachments.
You can construct a message using
email.message.Message
directly, but instead I'd recommend using a subclass fromemail.mime.*
to get you off the ground faster.Build a plaintext message
import email.mime.text msg = email.mime.text.MIMEText('Hello Friend') # mimetype: text/plain msg['Subject'] = 'Greetings' msg['To'] = 'user1@example.com'Build an html message
import email.mime.text msg = email.mime.text.MIMEText('Hello Friend', _subtype='html') # mimetype: text/html msg['Subject'] = 'Greetings' msg['To'] = 'user1@example.com'Formatting To/Cc/Bcc
To/Cc/Bcc are written to the header as dictionary keys.msg = email.mime.text.MIMEText('Hi') msg['To'] = 'user1@example.com' msg['Cc'] = 'user2@example.com' msg['Bcc'] = 'user3@example.com'
The format of these headers should match RFC-2822 https://tools.ietf.org/html/rfc2822.html
- emails are comma-separated
- emails can be specified in two formats
jdoe@example.com
John Doe <jdoe@example.com>
- header fields exceeding XX characters should be wrap text onto following line using
\r\n\t
(RFC-2822 section-2.2.3)msg['Bcc'] = ( 'john doe <john.doe@example.com,\r\n' '\tjane doe <jane.doe@example.com,\r\n' '\tuser@example.com' )
sending email
smtplib
smtplib is used to communicate with an existing SMTP server to send your mail.
Connection requirements may vary from server to server. Some more examples:
No SSL
import email.mime.text import smtplib msg = email.mime.text.MIMEText('hi') with smtplib.SMTP('smtp.gmail.com', 465) as smtp: smtp.ehlo() smtp.login('user@example.com', 'password') smtp.sendmail('from_user@example.com', ['to_user@example.com'], msg.as_string())SSL/TLS from start
import email.mime.text import smtplib msg = email.mime.text.MIMEText('hi') # uses SSL from start with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp: smtp.ehlo() smtp.login('user@example.com', 'password') smtp.sendmail('from_user@example.com', ['to_user@example.com'], msg.as_string())SSL/TLS after initial connection4
import email.mime.text import smtplib msg = email.mime.text.MIMEText('hi') with smtplib.SMTP('smtp.gmail.com', 465) as smtp: smtp.ehlo() smtp.starttls() smtp.login('user@example.com', 'password') smtp.sendmail('from_user@example.com', ['to_user@example.com'], msg.as_string())NOTE:
Unfortunately, it is incapable of extracting information from your email message headers, so you'll need to write a parser, or re-enter all of the recipients.
WARNING:
If you supporting python2, SMTP object must connect within try/finally to handle closing the connection.