Python SMTP Sending Email
SMTP (Simple Mail Transfer Protocol) is a simple mail transfer protocol. It is a set of rules for transferring mail from a source address to a destination address, which controls the way mail is relayed.
Python's smtplib provides a convenient way to send emails. It is a simple wrapper around the SMTP protocol.
The syntax for creating an SMTP object in Python is as follows:
import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )
Parameter description:
- host: SMTP server host. You can specify the IP address or domain name of the host, such as: example.com. This is an optional parameter.
- port: If you provide the host parameter, you need to specify the port number used by the SMTP service. Generally, the SMTP port number is 25.
- local_hostname: If SMTP is on your local machine, you only need to specify the server address as localhost.
The Python SMTP object uses the sendmail method to send emails. The syntax is as follows:
SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options])
Parameter description:
- from_addr: Sender's email address.
- to_addrs: A list of strings, the email addresses to send to.
- msg: The message to send.
Note the third parameter here: msg is a string representing the email. We know that an email generally consists of a subject, sender, recipient, email content, attachments, etc. When sending an email, pay attention to the format of msg. This format is the format defined in the SMTP protocol.
Example
The following example requires that you have an SMTP-supporting service installed on your machine, such as sendmail.
The following is a simple example of sending an email using Python:
Example
import smtplib
from email.mime.text import MIMEText
from email.header import Header
sender = 'from@example.com'
receivers = ['429240967@qq.com']
message = MIMEText('Python email sending test...', 'plain', 'utf-8')
message['From'] = Header("Example", 'utf-8')
message['To'] = Header("Test", 'utf-8')
subject = 'Python SMTP email test'
message['Subject'] = Header(subject, 'utf-8')
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message.as_string())
print "Email sent successfully"
except smtplib.SMTPException:
print "Error: Unable to send email"
We use three quotes to set the email information. A standard email requires three header fields:From, To, andSubject, each piece of information is separated by a blank line.
We instantiate the SMTP object of the smtplib modulesmtpObjto connect to the SMTP server, and usesendmailmethod to send the message.
Run the above program. If you have installedsendmail (mail transfer agent), it will output:
$ python test.py
邮件发送成功
Check your inbox (usually in the spam folder) to see the email:

If we do not have sendmail access on our machine, we can also use SMTP access from other email service providers (QQ, NetEase, Google, etc.).
Example
import smtplib
from email.mime.text import MIMEText
from email.header import Header
mail_host="smtp.XXX.com"
mail_user="XXXX"
mail_pass="XXXXXX"
sender = 'from@example.com'
receivers = ['429240967@qq.com']
message = MIMEText('Python email sending test...', 'plain', 'utf-8')
message['From'] = Header("Example", 'utf-8')
message['To'] = Header("Test", 'utf-8')
subject = 'Python SMTP email test'
message['Subject'] = Header(subject, 'utf-8')
try:
smtpObj = smtplib.SMTP()
smtpObj.connect(mail_host, 25)
smtpObj.login(mail_user,mail_pass)
smtpObj.sendmail(sender, receivers, message.as_string())
print "Email sent successfully"
except smtplib.SMTPException:
print "Error: Unable to send email"
Sending HTML-format emails with Python
The difference between sending HTML-formatted emails and plain-text emails in Python is that the `_subtype` in MIMEText is set to 'html'. The specific code is as follows:
Example
import smtplib
from email.mime.text import MIMEText
from email.header import Header
sender = 'from@example.com'
receivers = ['429240967@qq.com']
mail_msg = """<p>Python email sending test...</p>
<p><a href="http://www.example.com">This is a link</a></p>"""
message = MIMEText(mail_msg, 'html', 'utf-8')
message['From'] = Header("Example", 'utf-8')
message['To'] = Header("Test", 'utf-8')
subject = 'Python SMTP email test'
message['Subject'] = Header(subject, 'utf-8')
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message.as_string())
print "Email sent successfully"
except smtplib.SMTPException:
print "Error: Unable to send email"
Run the above program. If you have sendmail installed, it will output:
$ python test.py
邮件发送成功
Check your inbox (usually in the spam folder) to see the email:

Python Sending Emails with Attachments
To send an email with attachments, first create a MIMEMultipart() instance, then construct the attachment. If there are multiple attachments, you can construct them in sequence, and finally send it using smtplib.smtp.
Example
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
sender = 'from@example.com'
receivers = ['429240967@qq.com']
message = MIMEMultipart()
message['From'] = Header("Example", 'utf-8')
message['To'] = Header("Test", 'utf-8')
subject = 'Python SMTP email test'
message['Subject'] = Header(subject, 'utf-8')
message.attach(MIMEText('This is a Example Python email sending test...', 'plain', 'utf-8'))
att1 = MIMEText(open('test.txt', 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
att1["Content-Disposition"] = 'attachment; filename="test.txt"'
message.attach(att1)
att2 = MIMEText(open('example.txt', 'rb').read(), 'base64', 'utf-8')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="example.txt"'
message.attach(att2)
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message.as_string())
print "Email sent successfully"
except smtplib.SMTPException:
print "Error: Unable to send email"
$ python test.py
邮件发送成功
Check your inbox (usually in the spam folder) to see the email:

Adding Images in HTML Text
In HTML email bodies, adding external links is generally ineffective with email service providers. An example of correctly adding images is as follows:
Example
import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
sender = 'from@example.com'
receivers = ['429240967@qq.com']
msgRoot = MIMEMultipart('related')
msgRoot['From'] = Header("Example", 'utf-8')
msgRoot['To'] = Header("Test", 'utf-8')
subject = 'Python SMTP email test'
msgRoot['Subject'] = Header(subject, 'utf-8')
msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)
mail_msg = """<p>Python email sending test...</p>
<p><a href="http://www.example.com">Example Tutorial Link</a></p>
<p>Image demonstration:</p>
<p><img src="cid:image1"></p>"""
msgAlternative.attach(MIMEText(mail_msg, 'html', 'utf-8'))
fp = open('test.png', 'rb')
msgImage = MIMEImage(fp.read())
fp.close()
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, msgRoot.as_string())
print "Email sent successfully"
except smtplib.SMTPException:
print "Error: Unable to send email"
$ python test.py
邮件发送成功
Check your inbox (if it is in the spam folder, you may need to move it to the inbox for proper display), and you can see the email:

Sending Using a Third-party SMTP Service
Here we use the SMTP service of QQ Mail (you can also use 163, Gmail, etc.). The following configuration is required:

QQ Mail sets the password by generating an authorization code:

QQ Mail SMTP server address: smtp.qq.com, SSL port: 465.
In the following example, you need to modify: sender email (your QQ email), password, recipient email (you can send to yourself).
QQ SMTP
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
my_sender='429240967@qq.com'
my_pass = 'xxxxxxxxxx'
my_user='429240967@qq.com'
def mail():
ret=True
try:
msg=MIMEText('Fill in the email content','plain','utf-8')
msg['From']=formataddr(["FromExample",my_sender])
msg['To']=formataddr(["FK",my_user])
msg['Subject']="Example sending email test"
server=smtplib.SMTP_SSL("smtp.qq.com", 465)
server.login(my_sender, my_pass)
server.sendmail(my_sender,[my_user,],msg.as_string())
server.quit()
except Exception:
ret=False
return ret
ret=mail()
if ret:
print("Email sent successfully")
else:
print("Email sending failed")
$ python test.py
邮件发送成功
After successful sending, log in to the recipient's mailbox to view:

For more information, please refer to:https://docs.python.org/2/library/email-examples.html。
Other Extensions