当前位置:网站首页>SMTP automatic mail sending function code
SMTP automatic mail sending function code
2022-07-24 09:53:00 【Salted fish also have dreams】
SMTP Automatic email function
I also followed all kinds of blogs to search out step by step , There may be various problems when setting up the mailbox , Please refer to my other blogs for settings
https://blog.csdn.net/ly021499/article/details/82423019
https://blog.csdn.net/ly021499/article/details/80943030
The following code integrates the functions of generating test reports and automatically sending emails , A new test report template is used , Personally, I think it's more beautiful , A download link is attached
link :https://pan.baidu.com/s/1kwh7nAdc-vC0NbEK4PfODA
Extraction code :j77w
#-*- coding: utf-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import BSTestRunner # Note that I am using BSTestRunner, The blog is attached with a download link
import unittest
import time
import os
'''
_(\_/)
,((((^`\
(((( (6 \
,((((( , \
,,,_ ,((((( /"._ ,`,
((((\\ ,... ,(((( / `-.-'
))) ;' `"'"'""(((( (
((( / ((( \
)) | |
(( | . ' |
)) \ _ ' `t ,.')
( | y;- -,-""'"-.\ \/
) / ./ ) / `\ \
|./ ( ( / /'
|| \\ //'|
|| \\ _//'||
|| )) |_/ ||
\_\ |_/ ||
`'" \_\
`'"
'''
# *﹏₯㎕﹍﹍ Define sending email ζั͡ޓއއއ๓º
def send_mail(new_file):
# Email address
sender = Sender
# Receiving mailbox
receiver = Receiver
# Open mail
efile = open(new_file, 'rb')
email_body = efile.read()
efile.close()
# Instantiate an example with attachments
message = MIMEMultipart()
# Define the content of the message body
message.attach(MIMEText(email_body, _subtype='html', _charset='utf-8'))
# Define header
message['From'] = Sender
message['To'] = Receiver
# Define email subject
message['Subject'] = EmailTitle
# Define the sending time ( Undefined email clients may not display the sending time )
message['date'] = time.strftime('%a, %d %b %Y %H:%M:%S %z')
att = MIMEText(email_body, _subtype='base64', _charset='utf-8')
# Structural annex , Send... In the current directory test.txt file
att["Content-Type"] = 'application/octet-stream'
# there filename You can write whatever you want , What's the name , What's the name in the email
att["Content-Disposition"] = 'attachment; filename=%s' %AttName
message.attach(att)
# Connect SMTP The server
smtp = smtplib.SMTP()
smtp.connect(SMTP)
# User name, password
smtp.login(Sender, EmailPassword)
smtp.sendmail(sender, receiver, message.as_string())
smtp.quit()
print('*biubiubiu ₯㎕~~~ The missile was successfully launched , Shake ! Stupid people ޓއއއ ')
# *﹏₯㎕﹍﹍ Find the latest generated test report file ζั͡ޓއއއ๓º
def send_report(testreport):
result_dir = testreport
lists = os.listdir(result_dir)
lists.sort(key=lambda fn: os.path.getmtime(result_dir + "\\" + fn))
print (u' The latest missiles have been made , About to enter the launch program : '+lists[-1])
# Find the latest generated file
new_file = os.path.join(result_dir, lists[-1])
print(new_file)
# Call the email module
send_mail(new_file)
# *﹏₯㎕﹍﹍ Add use cases to the test suite ζั͡ޓއއއ๓º
def creatsuite():
testunit = unittest.TestSuite()
# Define the directory where the test file looks up
testcase_path = TestCasePath
# Definition discover Method parameters
discover = unittest.defaultTestLoader.discover(testcase_path, pattern='test*.py',top_level_dir=None)
# discover Use cases filtered out by method , Loop to test suite
for test_case in discover:
print(test_case)
testunit.addTests(test_case)
return testunit
def main():
now = time.strftime("%Y-%m-%d %H_%M")
# Path of report storage
report_path = ReportPath
# Build file full path
filename = report_path + ReportName + now + '.html'
# Open the report file
file = open(filename, 'wb')
# Set report header information
runner = BSTestRunner.BSTestRunner(stream=file, title=Title,
description=Description)
# Get the test suite and run
all_test_case = creatsuite()
runner.run(all_test_case)
# Close the generated report
file.close()
# Send report
send_report(ReportPath)
if __name__ == '__main__':
# Set the sending mailbox
Sender = '[email protected]' # Email account
# Set the receiving mailbox
Receiver= '[email protected]' # Receiving email password
# Set the email password
EmailPassword = 'xxxxxxx' # Fill in the client specific password you generated in your email here
# Set the subject line
EmailTitle = u" Automated test reports "
# Set the content of the message body
BodyContent = ' This email is sent automatically after executing the automation script , Please do not reply !'
# Set the email attachment name
AttName = "TestReport.html"
# Set up testCase Storage path
TestCasePath = os.path.dirname(os.path.abspath('.')) + '\\testcase'
# Set up SMTP The server -( It's for now QQ Mailbox server )
SMTP = "smtp.exmail.qq.com"
# Set the name of the report
ReportName = 'TestReport '
# Set the path of report storage
ReportPath = os.path.dirname(os.path.abspath('.')) + '\\reports\\'
# Set the report subject
Title = u'Big data platform'
# Set the report description
Description = u'This is the automation test report of the big data platform for reference only.'
# call main() Method to start the program
main()
边栏推荐
- Arduino drive lcd1602a
- RxJS Beginner Guide
- Raspberry Pie: serial port login does not display print information
- [don't bother to strengthen learning] video notes (IV) 1. What is dqn?
- PHP Basics - session control - Session
- Can the "self-help master" who has survived the economic crisis twice continue to laugh this time?
- [don't bother with intensive learning] video notes (III) 1. What is SARS?
- 程序的编译与链接
- [C language] implementation of three versions of address book small project (including source code)
- 财务数字化转型
猜你喜欢

Understanding of magnetic parameters in Hall sensors

What if path is deleted by mistake when configuring system environment variables?

Li Kou 300 longest increasing subsequence dynamic programming
![[STM32 learning] (18) STM32 realizes LCD12864 display - parallel implementation of 8-bit bus](/img/6b/b49b9e7fff62026a4818561d79fe3f.png)
[STM32 learning] (18) STM32 realizes LCD12864 display - parallel implementation of 8-bit bus

MySQL基础篇(一)-- SQL基础

Leetcode skimming: dynamic planning 03 (climb stairs with minimum cost)
![[STM32 learning] (12) STM32 realizes LCD1602 simple static reality](/img/78/954ebaae0cce5d9387e7032fa85e60.png)
[STM32 learning] (12) STM32 realizes LCD1602 simple static reality

【笔记】什么是内核/用户空间 从CPU如何运行程序讲起

Build practical product help documents to improve user satisfaction

Spark Learning: implement compact table command
随机推荐
Getting started with identityserver4
[don't bother with reinforcement learning] video notes (I) 3. Why use reinforcement learning?
Arduino- use millis() to do two (or more) things at the same time
It is reported that the prices of some Intel FPGA chip products have increased by up to 20%
Vscode failed to use SSH Remote Connection (and a collection of other problems)
Is CITIC Securities a safe and reliable securities firm? How to open an account?
Cess test online line! The first decentralized storage network to provide multiple application scenarios
Reading makes people improve my list
Build practical product help documents to improve user satisfaction
[C language] implementation of three versions of address book small project (including source code)
[STM32 learning] (9) stm32f1 general timer realizes simple breathing lamp
JS 84*148=b6a8 how many decimal places can you make both sides equal
Why add where exists() to the update select statement? And update with a with statement
In the envy of LETV, there is a "meaning crisis" of contemporary workers
Anti shake and throttling
Li Kou 300 longest increasing subsequence dynamic programming
Spark Learning: Spark implementation of distcp
[STM32 learning] (5) press the key to control the flow light (interrupt Implementation)
[Luogu p3426] SZA template (string) (KMP)
Scarcity in Web3: how to become a winner in a decentralized world