Python3 SMTP sends mail

Simple Mail Transfer Protocol, a simple messaging protocol, is a set of rules used to deliver messages from the source address to the destination address, which controls how letters are transited.

python's smtplib provides a convenient way to send e-mail. It simply encapsulates the smtp protocol.

Python creates smTP object syntax as follows:

import smtplib
smtpObj = smtplib.SMTP( [host [, port [, local_hostname]]] )

Description of the parameters:

  • Host: SMTP server host. Y ou can specify the host's ip address or domain name such w3cschool.cn, which is an optional parameter.
  • port: If you provide the host parameter, you need to specify the port number used by the SMTP service, which is typically 25.
  • local_hostname SMTP is on your computer, you only need to specify the server address as localhost.

The Python SMTP object sends messages using the sendmail method, as follows:

SMTP.sendmail(from_addr, to_addrs, msg[, mail_options, rcpt_options]

Description of the parameters:

  • from_addr: The address of the sender of the message.
  • to_addrs: String list, email send address.
  • msg: Send a message

Here's a look at the third argument, msg, which is a string that represents the message. W e know that the message is generally composed of the title, sender, recipient, content of the message, attachments, etc. , when sending the message, pay attention to the format of msg. This format is the format defined in the smtp protocol.

Instance

Here's a simple example of sending a message using Python:

#!/usr/bin/python3

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

sender = '[email protected]'
receivers = ['[email protected]']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

# 三个参数:第一个为文本内容,第二个 plain 设置文本格式,第三个 utf-8 设置编码
message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8')
message['From'] = Header("W3Cschool教程", '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 up message information, and standard messages require three header messages: From, To, and Subject, each of which is split directly using empty lines.

We connect to SMTP access by instantiation of the SMTP object smtpObj of the smtplib module and send messages using sendmail methods.

If you install sendmail on your computer, you will output:

$ python3 test.py 
邮件发送成功

Check out our inbox (usually in the trash) and you'll see the message:

Python3 SMTP sends mail

If we don't have sendmail access, 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 = '[email protected]'
receivers = ['[email protected]']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

message = MIMEText('Python 邮件发送测试...', 'plain', 'utf-8')
message['From'] = Header("W3Cschool教程", '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 html messages

Python sends html messages differently from messages that send plain text messages by setting the message in MIMEText _subtype html. Here's the code:

#!/usr/bin/python3

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

sender = '[email protected]'
receivers = ['[email protected]']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

mail_msg = """
<p>Python 邮件发送测试...</p>
<p><a href="http://www.w3cschool.cn">这是一个链接</a></p>
"""
message = MIMEText(mail_msg, 'html', 'utf-8')
message['From'] = Header("W3Cschool教程", '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: 无法发送邮件")

If you install sendmail on your computer, you will output:

$ python3 test.py 
邮件发送成功

Check out our inbox (usually in the trash) and you'll see the message:

Python3 SMTP sends mail


Python sends messages with attachments

To send a message with attachments, first create an MIMEMultipart() instance, then construct the attachment, if there are multiple attachments, you can construct it in turn, and finally send it 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 = '[email protected]'
receivers = ['[email protected]']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

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

#邮件正文内容
message.attach(MIMEText('这是W3Cschool教程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,传送当前目录下的 w3cschool.txt 文件
att2 = MIMEText(open('w3cschool.txt', 'rb').read(), 'base64', 'utf-8')
att2["Content-Type"] = 'application/octet-stream'
att2["Content-Disposition"] = 'attachment; filename="w3cschool.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 out our inbox (usually in the trash) and you'll see the message:

Python3 SMTP sends mail


Add a picture to the HTML text

The general mail service provider in the HTML text of the message adds an outer chain that is not valid, and the example of the breakthrough being added correctly 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 = '[email protected]'
receivers = ['[email protected]']  # 接收邮件,可设置为你的QQ邮箱或者其他邮箱

msgRoot = MIMEMultipart('related')
msgRoot['From'] = Header("W3Cschool教程", '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.w3cschool.cn">W3Cschool教程链接</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 out our inbox (if you may need to move to your inbox to display it properly), you can see the message information:

Python3 SMTP sends mail

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