Python3 SMTP sends mail


SMTP (Simple Mail Transfer Protocol) is a simple mail transfer protocol. It is a set of rules for transmitting mail from a source address to a destination address. It controls the transfer method of letters.

Python's smtplib provides a very convenient way to send emails. It simply encapsulates the SMTP protocol.

The syntax for Python to create an SMTP object 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: w3cschool.cc. 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: Email sending or address.

  • to_addrs: string list, email sending address.

  • msg: Send a message

Pay attention to the third parameter here, msg is a string, representing an email. We know that emails generally consist of a title, 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 is a simple example of using Python to send emails:

#!/usr/bin/python3

import smtplib
from email.mime.text import MIMEText
from email.header import Header

sender = 'from@php.cn'
receivers = ['429240967@qq.com']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

# 三个参数:第一个为文本内容,第二个 plain 设置文本格式,第三个 utf-8 设置编码
message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8')
message['From'] = Header("php中文网", 'utf-8')
message['To'] =  Header("测试", 'utf-8')

subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')


try:
    smtpObj = smtplib.SMTP('localhost')
    smtpObj.sendmail(sender, receivers, message.as_string())
    print ("邮件发送成功")
except smtplib.SMTPException:
    print ("Error: 无法发送邮件")

We use three quotation marks to set the email information. Standard emails require three header information:

From, To, and Subject, each information is directly separated by a blank line.

We connect to SMTP access by instantiating the SMTP object

smtpObj of the smtplib module and use the sendmail method to send information.

Execute the above program. If you install sendmail locally, it will output:

$ python3 test.py 
邮件发送成功

Check our inbox (usually in the trash), you can view the email information:

1029.jpg

If we do not have sendmail access locally, we can also use SMTP access from other service providers (QQ, NetEase, Google, etc.).

#!/usr/bin/python3

import smtplib
from email.mime.text import MIMEText
from email.header import Header

# 第三方 SMTP 服务
mail_host="smtp.XXX.com"  #设置服务器
mail_user="XXXX"    #用户名
mail_pass="XXXXXX"   #口令 


sender = 'from@php.cn'
receivers = ['429240967@qq.com']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8')
message['From'] = Header("php中文网", 'utf-8')
message['To'] =  Header("测试", 'utf-8')

subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')


try:
    smtpObj = smtplib.SMTP() 
    smtpObj.connect(mail_host, 25)    # 25 为 SMTP 端口号
    smtpObj.login(mail_user,mail_pass)
    smtpObj.sendmail(sender, receivers, message.as_string())
    print ("邮件发送成功")
except smtplib.SMTPException:
    print ("Error: 无法发送邮件")


Use Python to send emails in HTML format

The difference between sending emails in HTML format with Python and sending plain text messages is to set _subtype in MIMEText to html. The specific code is as follows:

#!/usr/bin/python3

import smtplib
from email.mime.text import MIMEText
from email.header import Header

sender = 'from@php.cn'
receivers = ['429240967@qq.com']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

mail_msg = """
<p>Python 邮件发送测试...</p>
<p><a href="http://www.php.cn">这是一个链接</a></p>
"""
message = MIMEText(mail_msg, 'html', 'utf-8')
message['From'] = Header("php中文网", 'utf-8')
message['To'] =  Header("测试", 'utf-8')

subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')


try:
    smtpObj = smtplib.SMTP('localhost')
    smtpObj.sendmail(sender, receivers, message.as_string())
    print ("邮件发送成功")
except smtplib.SMTPException:
    print ("Error: 无法发送邮件")

Execute the above program. If you install sendmail locally, it will output:

$ python3 test.py 
邮件发送成功

Check our inbox (usually in the trash) and you can see it Email information:

1030.jpg


Python Send an email with an attachment

To send an email with an attachment, you must first create a MIMEMultipart() instance and then construct the attachment. , if there are multiple attachments, they can be constructed sequentially and finally sent using smtplib.smtp.

#!/usr/bin/python3

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header

sender = 'from@php.cn'
receivers = ['429240967@qq.com']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

#创建一个带附件的实例
message = MIMEMultipart()
message['From'] = Header("php中文网", 'utf-8')
message['To'] =  Header("测试", 'utf-8')
subject = 'Python SMTP 邮件测试'
message['Subject'] = Header(subject, 'utf-8')

#邮件正文内容
message.attach(MIMEText('这是php中文网Python 邮件发送测试……', 'plain', 'utf-8'))

# 构造附件1,传送当前目录下的 test.txt 文件
att1 = MIMEText(open('test.txt', 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
# 这里的filename可以任意写,写什么名字,邮件中显示什么名字
att1["Content-Disposition"] = 'attachment; filename="test.txt"'
message.attach(att1)

# 构造附件2,传送当前目录下的 php.txt 文件
att2 = MIMEText(open('php.txt', 'rb').read(), 'base64', 'utf-8')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="php.txt"'
message.attach(att2)

try:
    smtpObj = smtplib.SMTP('localhost')
    smtpObj.sendmail(sender, receivers, message.as_string())
    print ("邮件发送成功")
except smtplib.SMTPException:
    print ("Error: 无法发送邮件")
$ python3 test.py 
邮件发送成功

Check our inbox (usually in the trash) and you can view the email information:

1031.jpg


Add pictures to the HTML text

It is invalid for general email service providers to add external links in the HTML text of the email. An example of correctly adding a breakthrough is as follows:

#!/usr/bin/python3

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@php.cn'
receivers = ['429240967@qq.com']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

msgRoot = MIMEMultipart('related')
msgRoot['From'] = Header("php中文网", 'utf-8')
msgRoot['To'] =  Header("测试", 'utf-8')
subject = 'Python SMTP 邮件测试'
msgRoot['Subject'] = Header(subject, 'utf-8')

msgAlternative = MIMEMultipart('alternative')
msgRoot.attach(msgAlternative)


mail_msg = """
<p>Python 邮件发送测试...</p>
<p><a href="http://www.php.cn">php中文网链接</a></p>
<p>图片演示:</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()

# 定义图片 ID,在 HTML 文本中引用
msgImage.add_header('Content-ID', '<image1>')
msgRoot.attach(msgImage)

try:
    smtpObj = smtplib.SMTP('localhost')
    smtpObj.sendmail(sender, receivers, msgRoot.as_string())
    print ("邮件发送成功")
except smtplib.SMTPException:
    print ("Error: 无法发送邮件")
$ python3 test.py 
邮件发送成功

Check our inbox (if it is in the trash, it may need to be moved to the inbox), you can view the email information:

1032.jpg

For more information, please refer to: https://docs.python.org/3/ library/email-examples.html.