Home > Backend Development > Python Tutorial > Example of how Python3 uses SMTP protocol to send E-mail emails

Example of how Python3 uses SMTP protocol to send E-mail emails

黄舟
Release: 2017-10-02 09:43:14
Original
3428 people have browsed it

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. The following article mainly introduces how Python3 uses the SMTP protocol to send E-mail emails. Friends in need can refer to it.

Preface

This article mainly introduces you to the relevant content about Python3 using SMTP protocol to send emails. It also introduces how to use python program to Before specifying an email address to send an email, we need to introduce some knowledge about email.

Email has a longer history than the Web. Until now, Email is also a very widely used service on the Internet.

Almost all programming languages ​​support sending and receiving email, but, wait, before we start writing code, it is necessary to understand how email works on the Internet.

Assume that our own email address is me@163.com and the other party’s email address is friend@sina.com. Now we use software such as Outlook or Foxmail to write the email and fill in the other party’s email address. Email address, click "Send", and the email will be sent. These email software are called MUA: Mail User Agent - Mail User Agent.

Emails sent from MUA do not reach the other party's computer directly, but are sent to MTA: Mail Transfer Agent - Mail transfer agent, which is those Email service providers, such as NetEase, Sina, etc. Since our own email is 163.com, the email is first delivered to the MTA provided by NetEase, and then sent by NetEase's MTA to the other service provider, which is Sina's MTA. This process may also pass through other MTAs, but we don't care about the specific route, we only care about the speed.

After the email reaches Sina's MTA, since the other party uses the mailbox of @sina.com, Sina's MTA will deliver the email to the final destination of the email: MDA: Mail Delivery Agent——Mail Delivery Agent . After the email reaches MDA, it lies quietly on a server of Sina and is stored in a file or special database. We call this place where emails are stored for a long time an email box. To get the mail, the other party must use MUA to get the mail from the MDA to his or her computer.

So, the journey of an email is:

Sender-> MUA -> MTA -> MTA -> Several MTAs - > MDA <- MUA <- Recipient

With the above basic concepts, you need to write a program to send and receive emails, which is essentially:

1. Write MUA to send emails to MTA.

2. Write MUA to receive emails from MDA.

When sending emails, the protocol used by the MUA and MTA is SMTP: Simple Mail Transfer Protocol. The subsequent MTA also uses the SMTP protocol to another MTA.

When receiving emails, MUA and MDA use two protocols: POP: Post Office Protocol, the current version is 3, commonly known as POP3; IMAP: Internet Message Access Protocol, the current version is 4, the advantage is that not only can Mail, you can also directly operate the mail stored on the MDA, such as moving it from the inbox to the trash, etc.

When the email client software sends emails, it will ask you to configure the SMTP server first, that is, which MTA you want to send to. Assuming you are using 163's email address, you cannot send directly to Sina's MTA because it only serves Sina users. Therefore, you have to fill in the SMTP server address provided by 163: smtp.163.com, in order to prove that you are 163 For users, the SMTP server also requires you to fill in your email address and email password, so that the MUA can normally send emails to the MTA through the SMTP protocol.

Similarly, when receiving emails from MDA, the MDA server also requires verification of your email password to ensure that no one will pretend to be you to receive your emails. Therefore, email clients such as Outlook will ask you to fill in POP3 Or IMAP server address, email address and password, so that MUA can successfully obtain emails from MDA through POP or IMAP protocol.

Finally, special note: Currently, most email service providers need to manually turn on the SMTP sending and POP receiving functions, otherwise they are only allowed to log in on the web page:

For example, QQ mailbox

Next, we start our topic, how to send emails through python.

-------------------------------------------------- ------------------------------------

Send simply Text email

SMTP is a protocol for sending emails. Python has built-in support for SMTP and can send plain text emails, HTML emails, and emails with attachments.

Python supports SMTP with two modules, smtplib and email. Email is responsible for constructing emails, and smtplib is responsible for sending emails.

First, let’s construct the simplest plain text email:


from email.mime.text import MIMEText
msg = MIMEText(&#39;hello, this is axin...&#39;, &#39;plain&#39;, &#39;utf-8&#39;)
Copy after login

Note:When constructing the MIMEText object, the first parameter is the email body, and the second parameter is the subtype of MIME. Passing in 'plain' means plain text. The final MIME is 'text/plain', and finally UTF-8 encoding must be used to ensure multi-language compatibility.

We just have the body content, we also need to add header information to the email we want to send. The header information contains information such as the sender and recipient, as well as the subject of the email.


msg = MIMEText(&#39;hello, this is axin...&#39;, &#39;plain&#39;, &#39;utf-8&#39;) #邮件正文
msg[&#39;From&#39;] = _format_addr(&#39;阿鑫 <%s>&#39; % from_addr) #邮件头部,发送者信息
msg[&#39;To&#39;] = _format_addr(&#39;aa <%s>&#39; % to_addr) #接收者信息
msg[&#39;Subject&#39;] = Header(&#39;test&#39;, &#39;utf-8&#39;).encode() #邮件主题
Copy after login

After constructing the information we want to send, we only need to call the corresponding python function and send it through SMTP:


server = smtplib.SMTP(smtp_server, 25) #SMTP协议默认端口是25
server.set_debuglevel(1) #打印出和SMTP服务器交互的所有信息
server.login(from_addr, password) #登录SMTP服务器
server.sendmail(from_addr, [to_addr], msg.as_string()) #发送邮件
server.quit()
Copy after login

We use set_debuglevel(1) to print out all the information interacting with the SMTP server. The SMTP protocol is simply text commands and responses. The login() method is used to log in to the SMTP server. The sendmail() method is to send an email. Since it can be sent to multiple people at one time, a list is passed in. The email body is a str, as_string() Change the MIMEText object into str.

The complete code example is as follows:


from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr

import smtplib

def _format_addr(s): #格式化一个邮件地址
name, addr = parseaddr(s)
return formataddr((Header(name, &#39;utf-8&#39;).encode(), addr))

from_addr = &#39;fengxinlinux@sina.com&#39; #发送者邮箱地址
password = &#39;******&#39; #发送者邮箱密码,不告诉你密码=。=
to_addr = &#39;903087053@qq.com&#39; #接收者邮箱地址
smtp_server = &#39;smtp.sina.com&#39; #发送者所在的邮箱供应商的MTA地址
#from_addr = input(&#39;From: &#39;)
#password = input(&#39;Password: &#39;)
#to_addr = input(&#39;To: &#39;)
#smtp_server = input(&#39;SMTP server: &#39;)

msg = MIMEText(&#39;hello, this is axin...&#39;, &#39;plain&#39;, &#39;utf-8&#39;) #邮件正文
msg[&#39;From&#39;] = _format_addr(&#39;阿鑫 <%s>&#39; % from_addr) #邮件头部,发送者信息
msg[&#39;To&#39;] = _format_addr(&#39;axin <%s>&#39; % to_addr) #接收者信息
msg[&#39;Subject&#39;] = Header(&#39;test&#39;, &#39;utf-8&#39;).encode() #邮件主题


server = smtplib.SMTP(smtp_server, 25) # SMTP协议默认端口是25
server.set_debuglevel(1) #打印出和SMTP服务器交互的所有信息
server.login(from_addr, password) #登录SMTP服务器
server.sendmail(from_addr, [to_addr], msg.as_string()) #发送邮件
server.quit()
1
Copy after login

Run the program, we will find that a new email was received in the mailbox I tested mail.

#We will find that the other information is the same, but the recipient’s information is not the axin filled in our program.

Because many email service providers will automatically replace the recipient's name with the user's registered name when displaying the email, but the display of other recipients' names will not be affected.

When I was testing, sometimes the emails I sent were judged as spam by the email service provider and were directly placed in the trash. . . As for what will be considered spam, I have no idea. .

Send emails with attachments

#We have introduced how to send text emails above. With the above knowledge, send emails with attachments Email is actually very simple.

An email with attachments can be seen as an email containing several parts: text and each attachment itself. Therefore, you can construct a MIMEMultipart object to represent the email itself, and then add a MIMEText to it as the email body, and then continue. Just add the MIMEBase object representing the attachment:


# 邮件对象:
msg= MIMEMultipart()
msg[&#39;From&#39;] = _format_addr(&#39;阿鑫 <%s>&#39; % from_addr) #邮件头部,发送者信息
msg[&#39;To&#39;] = _format_addr(&#39;axin <%s>&#39; % to_addr) #接收者信息
msg[&#39;Subject&#39;] = Header(&#39;test&#39;, &#39;utf-8&#39;).encode() #邮件主题

# 邮件正文是MIMEText:
msg.attach(MIMEText(&#39;hello, this is axin...&#39;, &#39;plain&#39;, &#39;utf-8&#39;))

# 添加附件就是加上一个MIMEBase,从本地读取一个图片:
with open(&#39;/home/fengxin/图片/11.jpg&#39;,&#39;rb&#39;) as fhandle:
mime = MIMEBase(&#39;image&#39;,&#39;jpeg&#39;,filename=&#39;11.jpg&#39;)
mime.add_header(&#39;Content-Disposition&#39;, &#39;attachment&#39;, filename=&#39;11.jpg&#39;)
mime.add_header(&#39;Content-ID&#39;, &#39;<0>&#39;)
mime.add_header(&#39;X-Attachment-Id&#39;, &#39;0&#39;)
# 把附件的内容读进来:
mime.set_payload(fhandle.read())
# 用Base64编码:
encoders.encode_base64(mime)
# 添加到MIMEMultipart:
msg.attach(mime)
Copy after login

Then, follow the normal sending process to send the msg (note that the type has changed to MIMEMultipart), and you can receive it. Emails with attachments.

The complete code example is as follows:


from email import encoders
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase


import smtplib

def _format_addr(s): #格式化一个邮件地址
name, addr = parseaddr(s)
return formataddr((Header(name, &#39;utf-8&#39;).encode(), addr))

from_addr = &#39;你的邮箱地址&#39; #发送者邮箱地址
password = &#39;你的邮箱密码&#39; #发送者邮箱密码
to_addr = &#39;903087053@qq.com&#39; #接收者邮箱地址
smtp_server = &#39;smtp.sina.com&#39; #发送者所在的邮箱供应商的MTA地址
#from_addr = input(&#39;From: &#39;)
#password = input(&#39;Password: &#39;)
#to_addr = input(&#39;To: &#39;)
#smtp_server = input(&#39;SMTP server: &#39;)


msg= MIMEMultipart()
msg[&#39;From&#39;] = _format_addr(&#39;阿鑫 <%s>&#39; % from_addr) #邮件头部,发送者信息
msg[&#39;To&#39;] = _format_addr(&#39;axin <%s>&#39; % to_addr) #接收者信息
msg[&#39;Subject&#39;] = Header(&#39;test&#39;, &#39;utf-8&#39;).encode() #邮件主题

msg.attach(MIMEText(&#39;hello, this is axin...&#39;, &#39;plain&#39;, &#39;utf-8&#39;))

with open(&#39;/home/fengxin/图片/11.jpg&#39;,&#39;rb&#39;) as fhandle:
mime = MIMEBase(&#39;image&#39;,&#39;jpeg&#39;,filename=&#39;11.jpg&#39;)
mime.add_header(&#39;Content-Disposition&#39;, &#39;attachment&#39;, filename=&#39;11.jpg&#39;)
mime.add_header(&#39;Content-ID&#39;, &#39;<0>&#39;)
mime.add_header(&#39;X-Attachment-Id&#39;, &#39;0&#39;)
# 把附件的内容读进来:
mime.set_payload(fhandle.read())
# 用Base64编码:
encoders.encode_base64(mime)
# 添加到MIMEMultipart:
msg.attach(mime)

server = smtplib.SMTP(smtp_server, 25) # SMTP协议默认端口是25
server.set_debuglevel(1) #打印出和SMTP服务器交互的所有信息
server.login(from_addr, password) #登录SMTP服务器
server.sendmail(from_addr, [to_addr], msg.as_string()) #发送邮件
server.quit()
1
Copy after login

After running. The test mailbox received the email correctly, as shown in the figure:

##Summary

The above is the detailed content of Example of how Python3 uses SMTP protocol to send E-mail emails. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template