Teach you how to use Python to send email easily


Now the pace of life is speeding up, and the communication methods between people are also very different. In order to facilitate communication, e-mail has been produced. As we all know, e-mail is actually the same as sending and receiving data on the client and server. It has a function of sending and receiving. The communication protocols of e-mail are SMTP, POP3 and IMAP, and they all belong to tcp/ip protocol, like QQ mailbox we often use, Netease mailbox, these are the same model.


Editor: sublime text 3

Modules: SMTP lib and email


project implementation

1. Installation

pip install smtplib
pip install email

Note: there is a small hole here, that is, the installation of smtplib cannot be directly installed as above, which will not be installed. You have to install PyEmail first, because your smtplib is integrated into this module, just like the pilot module is integrated into PIL, and the other can be installed normally.


2. Open pop3 SMTP imap service and know the email authorization code

If you want to send e-mail to any mailbox, you must first open the above services to enable e-mail communication, and there must be an e-mail authorization code, such as QQ e-mail:

Open the QQ email, select set account, and then open the service.

After the authorization code is generated, click Save to open the authorization code. To obtain the authorization code, you only need to send SMS or dynamic token with your registered mobile phone number.


3. Build mail port and establish connection

import smtplib
sm=smtp.SMTP()  # Initialize connection
sm.connect('Mail server address','port')  #Establish connection
sm.login('Email account','Mailbox password/Authorization code')  #Login account
sm.sendmail('Mail sender','Mail recipient','Mail content') #Send mail
sm.quit() #Close the connection and end the mail service

After knowing the above knowledge, let's try to log in. I take QQ email as an example:

Having such a logo indicates successful login. By the way, why didn't I configure the mail server port here, because the server has been configured for us. The default port is port 25. If you are worried about the security of mail, such as being intercepted by hackers, you can also use ssl link transmission:

Similarly, its port is configured by default. Its port number is 465. For security, we choose this option.


4. Build email content

Here we need to use the email module. As we all know, email can generally send a lot of things, such as text, pictures, files and so on. Let's have a look.

Many people learn python and don't know where to start.
After learning python and mastering the basic grammar, many people don't know where to find cases.
Many people who have done cases do not know how to learn more advanced knowledge.
So for these three types of people, I will provide you with a good learning platform, free video tutorials, e-books, and the source code of the course!
QQ group: 1156465813

1, Text

Import module

from email.mime.text import MIMEText

Fill text

Before that, we need to know its specific usage:

MIMEText('mail content ',' type ',' code ')

The message content is a string

Type: text/plain text/html

Code: utf-8#gbk

Construct text


Construct hypertext

MIMEText('<a href='www.baidu.com'>Click here for surprises</a>','text/html','utf-8')

Let's actually operate it.

Very successful. I received the email. It was 2091500484 that sent it to me. Of course, we only realize the simplest function,

We need to standardize its format, such as adding a beginning and an end to it. We need to import the module that builds the complete content of the email:

from email.header import Header

Then set the head, content and tail

msg1['From']=Header('Are you a pig?')  #Set sender nickname
msg1['To']=Header('hwhrr123321@163.com') #Set recipient nickname
msg1['Subject'] = Header('I'm a pig') #Set title

You can see, do you think it's very interesting? Come and have a try, hahaha...


2, Picture

After sending the text, we still want to send a picture. What should we do? Don't panic. At this time, you need to import the module that sends pictures first:

from email.mime.image import MIMEImage

Then we read the picture file and add it to the email.

ff=open('1.jpg','rb').read() #Open file
fd=MIMEImage(ff,'subtype')    #initialization
fd.add_header('Content-ID','1.jpg')  #Add to header

It can be seen that the picture is not displayed, so what's the matter? Oh, the original picture exists based on attachments, either html or attachments, but both need the support of the attachment module. Let's import the attachment module below:

from email.mime.multipart import MIMEMultipart

1. Insert the picture into html

That is, insert the picture into the body instead of the form of an attachment.

msg3 = MIMEMultipart('related')
msg3['From'] = 'Are you a pig?'
msg3['To'] = 'hwhrr123321@163.com'
msg3['Subject'] = 'I'm a pig'
msg4 = MIMEMultipart('alternative') #Build an attachment
msg3.attach(msg4)  #Introducing an attachment to another attachment
   <img src='cid:img' tittle='I am  pig'>
msg4.attach(MIMEText(text, 'html', 'utf-8')) #Insert html into the attachment
img = MIMEImage(ff.read())  #Read pictures into attachments
img.add_header('Content-ID','<img>') #Add picture header
msg3.attach(img)   #Add picture to attachment
sm.sendmail('2091500484@qq.com','hwhrr123321@163.com',msg3.as_string()) #send out

It can be seen that the process is still relatively complex, which is more troublesome than adding pictures with simple attachments. It is mainly due to the nesting of a layer of attachment structure.

2. Introduce the picture into the attachment

This is easier to achieve. As shown in the figure:


3, Documents

Before sending the file, we should consider that we should read it in binary form, and then add it to the attachment. It's easy to understand this.

1. Read the file

Here, we need to construct a base64 data stream reading file:

txt=MIMEText(open('fd.txt','rb').read(), 'base64', 'utf-8')


2. Set transmission type

txt["Content-Type"] = 'application/octet-stream'


3. Set attachment name

txt["Content-Disposition"] = 'attachment; filename = "fd.txt" '


4. Add the file to the attachment


Finally, the file is successfully added to the attachment.


Project summary

These are all my thoughts on email sending. In addition, if you want to visually show the process of email transmission, just add the following to the previous sentence of email server login:


In this way, all transmission processes can be printed on the terminal. Through the study of e-mail, it can greatly facilitate our life. You can use e-mail to set a schedule for you. Through the program, you can send e-mail on time every day. Isn't it very high? I hope today's article can give you a new understanding of e-mail.



Tags: Python Programming Linux

Posted by phpprog on Tue, 03 May 2022 03:22:00 +0300