We need to use Python to send various kinds of emails, how can we accomplish this? The answer is very simple: the smtplib and email libraries can be used to do this. smtplib and email can be used together to send all kinds of emails: plain text, HTML, attachments, group emails, emails with images, and so on. We'll explain the emailing functionality in a few sections.
smtplib is the module Python uses to send mail, and email is used to process mail messages.
Sending HTML-formatted emails
To send HTML-formatted emails, you need to set the _subtype of MIMEText to html, and the content of _text should be in HTML form.
import smtplib from import MIMEText sender = '***' receiver = '***' subject = 'python email test' smtpserver = 'smtp.' username = '***' password = '***' msg = MIMEText(u'''<pre> <h1> Hello </h1> </pre>''','html','utf-8') msg['Subject'] = subject smtp = () (smtpserver) (username, password) (sender, receiver, msg.as_string()) ()
Note: The code here does not incorporate exception handling and requires the reader to handle exceptions themselves.
Sending emails with pictures
Sending emails with images is done using MIMEMultipart and MIMEImage.
import smtplib from import MIMEMultipart from import MIMEText from import MIMEImage sender = '***' receiver = '***' subject = 'python email test' smtpserver = 'smtp.' username = '***' password = '***' msgRoot = MIMEMultipart('related') msgRoot['Subject'] = 'test message' msgText = MIMEText( '''<b> Some <i> HTML </i> text </b > and an image.<img alt="" src="cid:image1"/>good!''', 'html', 'utf-8') (msgText) fp = open('/Users/', 'rb') msgImage = MIMEImage(()) () msgImage.add_header('Content-ID', '<image1>') (msgImage) smtp = () (smtpserver) (username, password) (sender, receiver, msgRoot.as_string()) ()
Sending emails with attachments
Sending emails with attachments is done using MIMEMultipart and MIMEImage, focusing on constructing the header information.
import smtplib from import MIMEMultipart from import MIMEText sender = '***' receiver = '***' subject = 'python email test' smtpserver = 'smtp.' username = '***' password = '***' msgRoot = MIMEMultipart('mixed') msgRoot['Subject'] = 'test message' # Constructed accessories att = MIMEText(open('/Users/', 'rb').read(), 'base64', 'utf-8') att["Content-Type"] = 'application/octet-stream' att["Content-Disposition"] = 'attachment; filename=""' (att) smtp = () (smtpserver) (username, password) (sender, receiver, msgRoot.as_string()) ()