Interface automated testing - Python automatically sends test report mail encapsulation (details)


foreword

SMTP (Simple Mail Transfer Protocol), also known as Simple Mail Transfer Protocol, is a protocol that provides reliable and efficient email transmission.

The smtplib module of python provides a very convenient way to send emails, which simply encapsulates the smtp protocol.

Python mainly needs two modules to send emails: smtplib and email. These two modules are built-in libraries of python, and they can be used by importing them. smtplib is mainly responsible for sending mail, that is, an action of sending mail, such as connecting to the mailbox server, logging in to the mailbox, and sending mail.

Email is mainly responsible for constructing emails, which refers to some structures displayed on the email page, such as sender, recipient, subject, body, attachments, etc.

smtp authorization

It has been mentioned above that sending emails is based on the smtp service, so we need an account and authorization code that can log in to the smtp server. Here we take the qq mailbox as an example. After logging in to the qq mailbox, you can enable smtp in Settings > Account. Then send a text message to get the authorization code.

D1

send email

Description of some parameters involved:
Connect to the smtp server: smtplib.SMTP_SSL (smtp server address, port number)
Log in to the smtp server: smtp.login (smtp email address, authorization code for logging in to smtp)
Construct a mail object: MIMEMultipart()
Create mail content : MIMEText(email content, "plain", "utf8") two parameters text type, encoding format; if you want to send the email content in html format, replace plain (default) with html

Add relevant content to email: smg.attach (specific content), add email content
Set email subject: smg[“Subject”] = subject content
Set email sender: smg[“From”] = email address
Set email receiver From: smg["To"] = email address

Send mail: smtp.send_message (mail object, from_addr=sender’s mail address, to_addrs=recipient’s mail address) If there are multiple recipients, pass it to to_addrs in list format to create an
attachment: MIMEApplication (attachment content)
to create a picture : MIMEImage (image content), same as attachment

Set attachments or pictures, etc.: file_msg.add_header(_name, _value, **_params): Extended header settings, _name is the header field to be added, and _value is the value of the header.

msg.add_header('Content-ID', 'imgid') #设置图片ID
msg.add_header('Content-Disposition', 'attachment', filename='test.xlsx')#为附件添加一个标题
msg.add_header('Content-Disposition', 'attachment', filename=('utf-8', '', '中文标题')) #添加非ASCII字符时需指定编码
import smtplib
from email.mime.text import MIMEText    # 创建文本内容的邮件内容
from email.mime.multipart import MIMEMultipart  # 创建带附件的实例
from email.mime.application import MIMEApplication  # 用于创建附件的
from email.mime.image import MIMEImage   # 用于创建图片,与添加附件一样的,下面不做举例


# 第一步: 连接到smtp服务器
smtp = smtplib.SMTP_SSL("smtp.qq.com", 465)
smtp.login("[email protected]","afajccbab")

# 第二步:构建邮件
smg = MIMEMultipart()
text_smg = MIMEText("这是邮件文本内容", "plain", "utf8")	# 邮件内容
smg.attach(text_smg)	# 添加到邮件

# 添加附件
file_msg = MIMEApplication(open(r"C:\project\test\reports\report.html","rb").read())
file_msg.add_header('content-disposition', 'attachment', filename='report.html')
smg.attach(file_msg)	# 添加到邮件

smg["Subject"] = "测试测试"	# 主题
smg["From"] = "[email protected]" # 邮件内显示的发件人
smg["To"] = "[email protected]" # 邮件内显示的收件人

# 第三步发送邮件
smtp.send_message(smg, from_addr="[email protected]", to_addrs="[email protected]")

There are more usages, and those who are interested can study further.

Packaging and Application

The following is a simple encapsulation example, which can be optimized according to your own needs. You can even extract the email subject, sender, recipient, and smtp login mailbox authorization password and put them in the configuration file for maintenance.

import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication


def send_email(file_path):

    smtp = smtplib.SMTP_SSL("smtp.qq.com",465)
    smtp.login("[email protected]","smtp登录密码")

    smg = MIMEMultipart()
    text_smg = MIMEText("这是邮件文本内容", "plain", "utf8")
    smg.attach(text_smg)

    file_msg = MIMEApplication(open(file_path,"rb").read())
    file_msg.add_header('content-disposition', 'attachment', filename='report.html')
    smg.attach(file_msg)
    
    smg["Subject"] = "测试报告"
    smg["From"] = "[email protected]"
    smg["To"] = "[email protected]"
    smtp.send_message(smg,from_addr="[email protected]",to_addrs="[email protected]")

The test report is generated after the test case is run, so we can put the emailing step after the test report is generated:

import unittest
import os
from common.contants import CASE_DIR, REPORT_DIR
from common.send_email import send_email

# 第一步:创建测试套件
suite = unittest.TestSuite()

# 第二步加载用例到套件
loader = unittest.TestLoader()
suite.addTest(loader.discover(CASE_DIR))

report_path = os.path.join(REPORT_DIR, "report.html")
with open(report_path, "wb") as f:
    runner = HTMLTestRunner(stream=f,
                            title="24期的测试报告",
                            description="测试报告的描述信息。。。。。",
                            tester="MuSen"
                            )
    # 运行测试套件
    runner.run(suite)

# 执行完代码之后,发送报告
send_email(report_path)
The following is the most complete software test engineer learning knowledge architecture system diagram in 2023 that I compiled

1. From entry to mastery of Python programming

Please add a picture description

2. Interface automation project actual combat

Please add a picture description

3. Actual Combat of Web Automation Project

Please add a picture description

4. Actual Combat of App Automation Project

Please add a picture description

5. Resume of first-tier manufacturers

Please add a picture description

6. Test and develop DevOps system

Please add a picture description

7. Commonly used automated testing tools

Please add a picture description

Eight, JMeter performance test

Please add a picture description

9. Summary (little surprise at the end)

Struggle is the melody of the heart, and hard work is the movement played. No matter how difficult the road ahead is, as long as you maintain passion and perseverance, every struggle is a palace of growth. Only by believing in your own strength and daring to chase can you overcome the limitations of fate and open up the glory of life!

Struggle is the journey of life, and hard work is the driving force for moving forward. When difficulties and setbacks block the way, we must stick to our beliefs and fight bravely. Only by struggling can we surpass ourselves and realize the wings of our ideals. Don't give up, don't stop.

On the road of struggle, there is no need to be afraid of difficulties and challenges, because they are the ladder of growth. Believe in your ability, go forward bravely, and water the flowers of your dreams with sweat. As long as you keep fighting, you will eventually create your own brilliant life!

Guess you like

Origin blog.csdn.net/csdnchengxi/article/details/131961319
Recommended