Unittest接口和UI自動化測試框架中的發送郵件服務如何使用?

在寫Unittest接口和UI自動化測試的時候,需要封裝郵件模塊來進行發送郵件。如何做呢?簡單做一下整理。

1、在框架工具集中封裝send_mail.py

如圖,我的在common中封裝了send_mail.py
在這裏插入圖片描述
代碼如下:

#coding=utf-8
from email.mime.text import MIMEText
import time
import smtplib
import getpass
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import email
import os

def sendmain(file_path,mail_to = '[email protected]'):
    mail_from = '[email protected]' # 發送郵件賬號
    f = open(file_path,'rb')
    mail_body=f.read()
    f.close()
    
    #msg = email.MIMEMultipart.MIMEMultipart()
    msg = MIMEMultipart()

    # 構造MIMEBase對象做爲文件附件內容並附加到根容器  
    contype = 'application/octet-stream'  
    maintype, subtype = contype.split('/', 1)  
    
    ## 讀入文件內容並格式化  
    data = open(file_path, 'rb')
    file_msg = MIMEBase(maintype, subtype)
    file_msg.set_payload(data.read( ))  
    data.close( )  
    encoders.encode_base64(file_msg)
    
    ## 設置附件頭  
    basename = os.path.basename(file_path)  
    file_msg.add_header('Content-Disposition',  
                        'attachment', filename = basename)  
    msg.attach(file_msg)  
    print(u'msg 附件添加成功')
    
    msg1 = MIMEText(mail_body,_subtype='html',_charset='utf-8')
    msg.attach(msg1)
    
    if isinstance(mail_to,str):
        msg['To'] = mail_to
    else: 
        msg['To'] = ','.join(mail_to)
    msg['From'] = mail_from
    msg['Subject'] = u'zzzz項目接口自動化測試'
    msg['date']=time.strftime('%Y-%m-%d-%H_%M_%S')
    print(msg['date'])

    smtp = smtplib.SMTP()
    smtp.connect('smtp.126.com')
    smtp.login('[email protected]','123456') # 發送郵件賬號密碼
    smtp.sendmail(mail_from, mail_to, msg.as_string())
    smtp.quit()
    print('email has send out !')

if __name__=='__main__':
    sendmain('../report/2017-08-18-10_18_57_result.html')

2、 在主框架入口調用郵件模塊

在這裏插入圖片描述

    # HTML報告
    now = datetime.datetime.now().strftime('%Y-%m-%d_%H_%M_%S')
    htmlreport = reportpath + "/" + now + r"result.html"
    print("測試報告生成地址:%s"% htmlreport)
    fp = open(htmlreport, "wb")
    runner = HTMLTestRunner.HTMLTestRunner(stream=fp, verbosity=2, title="xxxx項目接口自動化測試報告", description="用例執行情況")
    # 調用add_case函數返回值
    runner.run(all_case)
    fp.close()
    time.sleep(2)
    sendmain(htmlreport, mail_to=['[email protected]']) # 填寫需要發送給對方郵件賬號,用逗號隔開,可寫多個
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章