Python realizes sending mail by itself. Come to Get this skill

Posted by phpBuddy on Fri, 14 Jan 2022 13:45:42 +0100

come to the point

In the process of automated testing, test results are generally sent to relevant personnel in the form of e-mail. Then, in Python, how to write code to send e-mail to the corresponding users?

At the same time, there are different forms when sending e-mail, such as text, HTML, picture attachment, non picture attachment, etc. How do these operate? Let's study together~

Send mail automatically SMTP

introduce

SMTP Chinese name is simple mail transfer protocol. It is a protocol that provides reliable and effective e-mail transmission. It can transmit e-mail information between systems.

SMTP is a mail service based on FTP file transfer service. It is mainly used for mail information transmission between systems and provides notification of letters.

SMTP is independent of specific transmission subsystem and only needs reliable and orderly data flow channel support. One of the important characteristics of SMTP is that it can transmit mail across the network, that is, "SMTP mail relay".

Using SMTP, mail transmission between the same network processing processes can be realized, and mail transmission between a processing process and other networks can also be realized through repeaters or gateways.

We take QQ mailbox as an example. If you need to send mail, you must first start the SMTP service.

Turn on SMTP service

  • Log in to QQ email and click settings;
  • Click account;

  • Click POP3/SMTP service as enabled;
  • Generate the authorization code according to the steps. The authorization code is generally 16 bits.

According to the above steps, the SMTP service can be started easily.

Property configuration of mail

Create a new Python file and write code:

# Mailbox property configuration

# Mailbox server
mailserver = 'smtp.qq.com' 
# Sender - I wrote this email casually
userName_SendMail = '666666666@qq.com'  
# Email sending authorization code - the authorization code generated according to step 4 for the sender's mailbox
userName_AuthCode = 'abcdefghijklmnop'
# Define the recipients of e-mail - I write it casually. If there are many recipients, it can be represented by a list
received_mail = ['888888888@qq.com','999999999@qq.com']  
 

If it is a QQ mailbox, the server is SMTP qq. COM, if it is 163 email, the server is SMTP 163.com, other e-mails can be queried by Baidu.

Send text mail

Let's send a simple text email first.

Guide Package:

You need to use the SMTPLIB library to connect the mailbox import smtplib. Library for handling mail content: email Mine, to send text mail, you need to import: from email mime. text import MIMEText.

# You need to use the SMTPLIB library to connect to your mailbox
import smtplib
# A library for handling mail content, email mine
from email.mime.text import MIMEText

# Mailbox property configuration

# Mailbox server
mailserver = 'smtp.qq.com' 
# Sender - I wrote this email casually
userName_SendMail = '666666666@qq.com'  
# Email sending authorization code - the authorization code generated according to step 4 for the sender's mailbox
userName_AuthCode = 'abcdefghijklmnop'
# Define the recipients of e-mail - I write it casually. If there are many recipients, it can be represented by a list
received_mail = ['888888888@qq.com','999999999@qq.com'] 

# Send a simple email and process the email content
content = 'This is a pure text message! This is a pure text message!'
# The definition of mail content in plain text is operated through MIMEText, and plain is the default text display form
email = MIMEText(content, 'plain', 'utf-8')  
email['Subject'] = 'This is the subject of the email'  # Define message subject
email['From'] = userName_SendMail  # Sender
email['To'] = ','.join(received_mail)  # Recipients (multiple recipients can be added. If there is only one recipient, the mailbox number can be written directly)


# Send mail

# The port number of QQ mailbox is 465. The port numbers of other mailboxes can be Baidu. Non QQ mailboxes generally use SMTP without SSL
smtp = smtplib.SMTP_SSL(mailserver, port=465) 
smtp.login(userName_SendMail, userName_AuthCode)
smtp.sendmail(userName_SendMail, ','.join(received_mail), email.as_string())

smtp.quit()
print('That's great. The email was sent successfully')

Send HTML mail

Sending other mail is similar to the above code. The attribute configuration of the mailbox and the sending mail part do not change. Only the processing part of the mail content needs to be modified.

Change MIMEText(content, 'plain', 'utf-8') to MIMEText(content, 'HTML', 'utf-8'), and plain is the default text display form.

# You need to use the SMTPLIB library to connect to your mailbox
import smtplib
# A library for handling mail content, email mine
from email.mime.text import MIMEText

# Mailbox property configuration

# Mailbox server
mailserver = 'smtp.qq.com' 
# Sender - I wrote this email casually
userName_SendMail = '666666666@qq.com'  
# Email sending authorization code - the authorization code generated according to step 4 for the sender's mailbox
userName_AuthCode = 'abcdefghijklmnop'
# Define the recipients of e-mail - I write it casually. If there are many recipients, it can be represented by a list
received_mail = ['888888888@qq.com','999999999@qq.com'] 

# Send an HTML message
content = """
<p>This is a letter HTML Text mail</p>
<p><a href="http://www.baidu. Com "> Click here to enter Baidu</a></p>
"""
email = MIMEText(content, 'HTML', 'utf-8')
email['Subject'] = 'This is the subject of the email_HTML'  # Define message subject
email['From'] = userName_SendMail  # Sender
email['To'] = ','.join(received_mail)  # addressee


# Send mail

# The port number of QQ mailbox is 465. The port numbers of other mailboxes can be Baidu. Non QQ mailboxes generally use SMTP without SSL
smtp = smtplib.SMTP_SSL(mailserver, port=465) 
smtp.login(userName_SendMail, userName_AuthCode)
smtp.sendmail(userName_SendMail, ','.join(received_mail), email.as_string())

smtp.quit()
print('That's great. The email was sent successfully')

Send attachment mail

Send the attachment email. The email sending form is changed to email = MIMEMultipart(), and the sent attachments are processed. The mail attachments need to be imported into mimemultipart, header and mimebase.

Guide Package:

  • from email.mime.multipart import MIMEMultipart
  • from email.header import Header
  • from email.mime.base import MIMEBase
# You need to use the SMTPLIB library to connect to your mailbox
import smtplib
# To process mail attachments, you need to import mimemultipart, header and mimebase
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.mime.base import MIMEBase
from email import encoders  # Coding format

# Mailbox property configuration
# Mailbox server
mailserver = 'smtp.qq.com' 
# Sender - I wrote this email casually
userName_SendMail = '666666666@qq.com'  
# Email sending authorization code - the authorization code generated according to step 4 for the sender's mailbox
userName_AuthCode = 'abcdefghijklmnop'
# Define the recipients of e-mail - I write it casually. If there are many recipients, it can be represented by a list
received_mail = ['888888888@qq.com','999999999@qq.com'] 

# Send attachments in mail
# Attachment configuration mailbox
email = MIMEMultipart()
email['Subject'] = 'This is the subject of the email_Non picture attachment'  # Define message subject
email['From'] = userName_SendMail  # Sender
email['To'] = ','.join(received_mail)  # Recipients (multiple recipients can be added. If there is only one recipient, the mailbox number can be written directly)

# Attachment handling
att = MIMEBase('application', 'octet-stream')  # standard
att.set_payload(open('Test file.txt', 'rb').read())
att.add_header('Content-Disposition', 'attachment', filename=Header('Test file.txt', 'gbk').encode())
encoders.encode_base64(att)
email.attach(att)


# Send mail
smtp = smtplib.SMTP_SSL(mailserver, port=465)  # The port number of QQ mailbox is 465. The port numbers of other mailboxes can be Baidu. Non QQ mailboxes generally use SMTP without SSL
smtp.login(userName_SendMail, userName_AuthCode)
smtp.sendmail(userName_SendMail, ','.join(received_mail), email.as_string())

smtp.quit()
print('That's great. The email was sent successfully')

Postscript

Python's e-mail sending is so careless that I'll write here. Please give me more advice. If the article is helpful to you, please leave your little heart! come on!

The technology industry should continue to learn. It is better not to fight alone in learning. It is better to be able to keep warm together, achieve each other and grow together. The effect of mass effect is very powerful. If we learn together and punch in together, we will have more motivation to learn and stick to it. You can join our testing technology exchange group: 914172719 (there are various software testing resources and technical discussions)

Let's give you a word of encouragement: when our ability is insufficient, the first thing to do is internal practice! When our ability is strong enough, we can look outside!

Finally, a supporting learning resource is also prepared for you. You can scan the QR code below on wechat and get a 216 page interview classic document of Software Test Engineer for free. And the corresponding video learning tutorials for free!, The materials include basic knowledge, Linux essentials, Shell, Internet program principles, Mysql database, special topics of packet capture tools, interface test tools, test advanced Python programming, Web automation test, APP automation test, interface automation test, advanced test continuation, test architecture, development test framework, performance test, security test, etc.

Friends who like software testing, if my blog is helpful to you and if you like my blog content, please click "like", "comment" and "collect" for three times!

Haowen recommendation

Job transfer interview, job hopping interview, these interview skills that software testers must know!

Interview experience: move bricks in first tier cities! Another software testing post, 5000 will be satisfied

Interviewer: I've worked for three years and have a preliminary test? I'm afraid your title of software test engineer should be enclosed in double quotation marks

What kind of person is suitable for software testing?

The man who left work on time was promoted before me

The test post changed jobs repeatedly and disappeared

As a test engineer with 1 year working experience, my suggestions before the interview are as follows

"After a year in office, the automation software test hired by high salary was persuaded to quit."

4 months of self-study software testing into Ali! How to move from functional testing to automation... What have I experienced

6000 yuan applied for the training course. Three months later, I successfully "cheated" into Tencent's big factory with a monthly salary of 15000 yuan

Topics: Python Back-end Programmer software testing IT