We usually need to use Python to send all kinds of emails. How can we achieve this requirement? The answer is actually very simple, smtplib and email libraries can help achieve this requirement. The combination of smtplib and email can be used to send all kinds of mail: normal text, HTML form, with attachments, group mail, mail with pictures, etc. We will explain the sending mail function in several sections here.
smtplib is a module used by Python to send emails, and email is used to process email messages.
Sending emails with attachments is to use the MIMEMultipart of email.mime.multipart and the MIMEImage of email.mime.image. The focus is to construct the message header information:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
sender = '***'
receiver = '***'
subject = 'python email test'
smtpserver = 'smtp.163.com'
username = '***'
password = '***'
msgRoot = MIMEMultipart('mixed')
msgRoot['Subject'] = 'test message'
# 构造附件
att = MIMEText(open('/Users/1.jpg', 'rb').read(), 'base64', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment; filename="1.jpg"'
msgRoot.attach(att)
smtp = smtplib.SMTP()
smtp.connect(smtpserver)
smtp.login(username, password)
smtp.sendmail(sender, receiver, msgRoot.as_string())
smtp.quit()
Note: The code here does not add exception handling, and readers need to handle exceptions themselves.