Automated test framework , Generally, a failure notification is sent to the tester after the execution fails . Common notification methods : Mail notification 、 Enterprise wechat notice 、 Nail notice, etc , Email notification is one of the most common and formal notification methods .
Let's talk this time Python How to send email notification in , We all know Python Built in right SMTP Support for , You can send plain text 、 Rich text 、HTML And so on , however SMTP It's a little complicated to write code .
So I hope to have a lightweight solution , Until I met yagmail.
With 163 Mailbox as an example , Before coding , We need to turn on SMTP service .
Manually add an authorization code . account number 、 Authorization code 、 The server address is used to connect to the login mailbox server .
stay Python Send email in ,yagmail Probably the easiest way to use it right now .yagmail Just a few lines of code , Can realize the function of sending mail . comparison zmail,yagmail The way to send email is more simple and elegant .
github: https://github.com/kootenpv/yagmail
Support at the same time python2 and python3 Two versions installed
pip install yagmail
pip3 install yagmail
It mainly introduces the two common carriers of sending text and sending attachments .
First, simply send a piece of text ,contents by list Structure to wrap text .
Code example :
import yagmail
# Connect to server
# user name 、 Authorization code 、 Server address
yag = yagmail.SMTP(user='[email protected]', password=' Authorization code ', host='smtp.163.com')
# next , adopt send() function , Send the mail out
contents = ['This is the body, and here is just text http://somedomain/image.png',
'You can find an audio file attached.', '/local/path/song.mp3']
yag.send('[email protected]', 'subject', contents)
# Close the connection
yag_server.close()
Available at the receiving end Mailing list, See the code just now to send an email , There is almost no delay in receiving emails .
The following code loads multiple test reports locally and sends them as attachments
Code example :
import yagmail
# Connect to server
# user name 、 Authorization code 、 Server address
yag = yagmail.SMTP(user='[email protected]', password=' Authorization code ', host='smtp.163.com')
# next , adopt send() function , Send the mail out
# Send object list
email_to = ['[email protected]', ]
email_title = ' Test report '
email_content = " This is the test report "
# Attachment list
email_attachments = ['./report-1652541422.html','./reports/report-1652540875.html']
# Send E-mail
yag.send(email_to, email_title, email_content, email_attachments)
# Close the connection
yag_server.close()
You can see two test reports in the attachment of the email , Click to preview .
It says Python Use in ymail Some basic uses for sending mail , And it is often used in my daily work , It is highly recommended that you use .