Web自動化【8】——python發送郵件示例(執行案例,生成HTML報告,發送測試報告郵件)

目錄展示:
在這裏插入圖片描述
代碼:

from HTMLTestRunner import HTMLTestRunner
import unittest
import time
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
import smtplib
import os


# 定義發送郵件
def send_mail(file):
    f = open(file, 'rb',).read()
    # f.close()
    att = MIMEText(f, 'base64', 'utf-8')
    att['content-type'] = 'application/octet-stream'
    att['content-disposition'] = "attachment; filename ='testing_result.html'"
    msg = MIMEText('各位好,附件是本次的測試報告,請查閱!謝謝', 'plain', 'utf-8')

    msg_all = MIMEMultipart('related')
    msg_all['Subject'] = Header('自動化測試報告', "utf-8")

    print('添加附件')
    msg_all.attach(att)
    print('添加成功')
    msg_all.attach(msg)

    smtp = smtplib.SMTP()
    smtp.connect('smtp.qq.com', 25)
    smtp.login('***@qq.com', '授權碼')
    smtp.sendmail('***@qq.com', '***@qq.com', msg_all.as_string())
    smtp.quit()
    print('email has send out!')


# 查找測試報告
def find_report(address):
    lists = os.listdir(address)
    # lists.sort(key=lambda fn: os.path.getmtime(address + '\\' + fn))
    file_new = os.path.join(address, lists[-1])
    print(file_new)
    return file_new


if __name__ == '__main__':
	# 測試案例目錄
    test_dir = 'D:\\pypypy2\\zidonghua\\uinttest\\test_project\\test_case'
    # 測試報告保存目錄
    address_report = 'D:\\pypypy2\\zidonghua\\uinttest\\test_project\\test_case\\report'
	# 在測試案例目錄加載以test開頭的案例集
    discover = unittest.defaultTestLoader.discover(test_dir, pattern='test*.py')
    now = time.strftime("%Y-%m-%d_%H_%M_%S")
    # 每次生成的報告絕對路徑和時間戳報告名稱
    filename = address_report + '\\' + now + 'mail_report.html'
    fp = open(filename, 'wb')
    runner = HTMLTestRunner(stream=fp, title='測試報告', description='用例執行情況' )
    # 執行已保存的案例集
    runner.run(discover) 
    fp.close()

    new_report = find_report(address_report)
    print(new_report)
    send_mail(new_report)

最終效果圖如下:
在這裏插入圖片描述
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章