Teach you how to use Python to easily send emails

Preface

Now the pace of life is accelerating, and the way of communication between people is different. In order to communicate more conveniently, e-mail has been generated. As we all know, e-mail is actually the same as sending and receiving data on the client side and the server side. A function of receiving mail, the communication protocol of e-mail is SMTP, POP3, IMAP, and they all belong to the tcp/ip protocol, like the QQ mailbox and Netease mailbox we often use, these are the same mode.

Many people learn python and don't know where to start.
Many people learn python and after mastering the basic grammar, they don't know where to find cases to get started.
Many people who have done case studies do not know how to learn more advanced knowledge.
For these three types of people, I will provide you with a good learning platform, free to receive video tutorials, e-books, and course source code! ??¤
QQ group: 828010317

ready

  • Editor: sublime text 3
  • Modules: smtplib and email

Project implementation

1. Installation

pip install smtplib 
pip install email 

Note: There is a small pit here, that is, installing smtplib cannot be installed directly as above, otherwise it will not be installed, you have to install PyEmail first, because your smtplib is integrated in this module, it is like the pillow module integrated in PIL The same, the other one can be installed normally.

2. Open pop3 SMTP imap service to understand the email authorization code

If you want to send an email to any mailbox, you must first activate the above services to allow the email to communicate, and you must have an email authorization code, such as QQ mailbox:

Open the QQ mailbox, select Settings--------Account, and then turn on the service.

After starting the service, click Generate Authorization Code and save the authorization code. To obtain the authorization code, you only need to send a text message or dynamic token with your registered mobile phone number.

3. Build a mail port and establish a connection

import smtplib 
sm=smtp.SMTP()  # 初始化连接 
sm.connect('邮件服务器地址','端口')  #建立连接 
sm.login('邮箱账号','邮箱密码/授权码')  #登陆账户 
sm.sendmail('邮件发送方','邮件接受方','邮件内容') #发送邮件 
sm.quit() #关闭连接,结束邮件服务 

After understanding the above knowledge, let's try to log in. Let me take QQ mailbox as an example:

There is such a logo to indicate a successful login. By the way, why did I not configure the mail server port here because the server has already configured it for us. The default port is 25. If you are worried about the security of the mail, for example, it will be Hackers intercept Hu, you can also use ssl link transmission:

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

4. Build the email content part

Here we need to use the email module. We all know that emails can generally send many things, such as text, pictures, files, etc., so let's take a look.

1. Text

Import module

from email.mime.text import MIMEText 

Fill text

Before that, we have to know its specific usage:

  • MIMEText('mail content','type','encoding')
  • The message content is a string
  • Type: text/plain text/html
  • Encoding: utf-8 gbk

Structure text

MIMEText('hello','text/plain','utf-8') 

Construct hypertext

MIMEText('<a href='www.baidu.com'>点击此处有惊喜</a>','text/html','utf-8') 

Let's do it now.

I received the email very successfully. It was the mailbox 2091500484 sent to me. Of course, we just realized the simplest function like this,

We need to standardize its format, such as adding a beginning and ending 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('你是猪吗')  #设置发件人昵称 
msg1['To']=Header('[email protected]') #设置收件人昵称 
msg1['Subject'] = Header('我是猪') #设置标题 

You can see, is it interesting? Come and try it, hahaha. . .

Two, pictures

After sending the text, we still want to send a picture. What should we do? Don’t panic. At this time, we need to import the picture sending module:

from email.mime.image import MIMEImage 

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

ff=open('1.jpg','rb').read() #打开文件 
fd=MIMEImage(ff,'subtype')    #初始化 
fd.add_header('Content-ID','1.jpg')  #添加到头部 

You can see that the picture is not displayed, so what's going on, oh, the original picture is 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 the html

That is, the picture is inserted into the body part, not in the form of an attachment.

msg3 = MIMEMultipart('related') 
msg3['From'] = '你是猪吗' 
msg3['To'] = '[email protected]' 
msg3['Subject'] = '我是猪' 
msg4 = MIMEMultipart('alternative') #构建一个附件 
msg3.attach(msg4)  #将附件引入到另一个附件 
text=""" 
   <html> 
   <body> 
   <img src='cid:img' tittle='I am  pig'> 
   </body> 
   </html> 
""" 
msg4.attach(MIMEText(text, 'html', 'utf-8')) #将html插入到附件中 
ff=open('2.jpg','rb') 
img = MIMEImage(ff.read())  #将图片读取到附件中 
ff.close() 
img.add_header('Content-ID','<img>') #添加图片头部 
msg3.attach(img)   #将图片添加到附件 
sm.sendmail('[email protected]','[email protected]',msg3.as_string()) #发送 
sm.quit() 

It can be seen that the process is still more complicated, and it is a bit more troublesome than simply adding pictures as attachments, mainly because of the nested attachment structure.

2. Import the picture into the attachment

This is easier to achieve. As shown:

Three, documents

Before sending the file, one of the issues we have to consider is that we need to read it in binary form, and then add it to the attachment. It is easy to understand this.

1. Read the file

Here we need to construct a base64 data stream to read the file:

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

2. Set the transmission type

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

3. Set the attachment name

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

4. Add the file to the attachment

msg6.attach(txt) 

Finally, the file was successfully added to the attachment.

Project summary

The above is all my thoughts about mail sending. In addition, if you want to visually display the process of mail transmission, just add the following sentence before the mail server login:

sm.set_debuglevel(1) 

In this way, all transmission processes can be printed on the terminal. Learning about emails can greatly facilitate our lives. You can use emails to set up a schedule for you. Through the program, you can send emails on time every day. Isn’t it very compelling? I hope this article can help today. Everyone has a new understanding of mail.

 

Guess you like

Origin blog.csdn.net/Python_sn/article/details/110885012