python接口自動化(三十)--html測試報告通過郵件發出去——中(詳解)


簡介

  上一篇,我們雖然已經將生成的最新的測試報告發出去了,但是MIMEText 只能發送正文,無法帶附件,因此我還需要繼續改造我們的代碼,實現可以發送帶有附件的郵件。發送帶附件的需要導入另外一個模塊 MIMEMultipart。還有就是測

試負責人不止一個人,需要將測試報告發給多個人,也就是多個收件人。這篇主要是圍繞這兩個主題進行講解的。

 大致思路

(一)帶有附件發送郵件

1、導入模塊 MIMEMultipart

from email.mime.multipart import MIMEMultipart

2、先讀取要發送文件的內容,file_new 是測試報告路徑的參數名

 

3、下圖紅色框框 file_name 參數是發送的附件重新命名

 

4、file_new 是測試報告路徑的參數名,發送郵件是將其傳入

5、運行結果

6、查看收件箱

(二)發送給多個收件人

上面都是發給一個收件人,那么如何一次發給多個收件人呢?其實是非常簡單的,只需改兩個小地方,即可,從這里就可以看出python的強大之處。
1、源碼

2、仿造修改

3、運行結果

4、收件箱查看

公司郵箱

 

 

QQ郵箱

 

參考代碼

# coding=utf-8
#1.先設置編碼,utf-8可支持中英文,如上,一般放在第一行

#2.注釋:包括記錄創建時間,創建人,項目名稱。
'''
Created on 2019-5-7
@author: 北京-宏哥
Project:學習和使用將測試報告通過郵件發出去且郵件帶有附件
'''
#3.導入unittest模塊
import unittest
import os
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
import smtplib
#4.編寫測試用例和斷言
def all_case():
    # 待執行用例的目錄
    #case_dir = "C:\\Users\\DELL\\PycharmProjects\\honggetest\\case"
    case_dir = os.path.join(os.getcwd(), "case")
    testcase = unittest.TestSuite()
    discover = unittest.defaultTestLoader.discover(case_dir,
                                                   pattern="test*.py",
                                                   top_level_dir=None)
    # #discover方法篩選出用例,循環添加到測試套件中
    # for test_suit in discover:
    #     for test_case in test_suit:
    #         #添加用力到testcase
    #         testcase.addTests(test_case)
    # print(testcase)
    testcase.addTests(discover)  # 直接加載 discover    可以兼容python2和3
    print(testcase)
    return testcase
# ==============定義發送郵件==========
def send_mail(file_new):
    #-----------1.跟發件相關的參數------
    smtpserver = 'smtp.mxhichina.com'                #發件服務器
    port = 0                      #端口
    username = 'nXXX@ceXx.cn'  #發件箱用戶名
    password = 'ceXXx@@123'        #發件箱密碼
    sender = 'XXly@cedex.cn'    #發件人郵箱
    receiver = ['hongge@com.cn','1918991791@qq.com'] #收件人郵箱
    # ----------2.編輯郵件的內容------
    #讀文件
    f = open(file_new, 'rb')
    mail_body = f.read()
    f.close()
    # 郵件正文是MIMEText
    body = MIMEText(mail_body, 'html', 'utf-8')
    # 郵件對象
    msg = MIMEMultipart()
    msg['Subject'] = Header("自動化測試報告", 'utf-8').encode()#主題
    msg['From'] = Header(u'測試機 <%s>'%sender)                #發件人
    msg['To'] = Header(u'測試負責人 <%s>'%receiver)            #收件人
    msg['To'] = ';'.join(receiver)
    msg['date'] = time.strftime("%a,%d %b %Y %H:%M:%S %z")
    msg.attach(body)
    # 附件
    att = MIMEText(mail_body, "base64", "utf-8")
    att["Content-Type"] = "application/octet-stream"
    att["Content-Disposition"] = 'attachment; filename="test_report.html"'
    msg.attach(att)
    # ----------3.發送郵件------
    try:
        smtp = smtplib.SMTP()
        smtp.connect(smtpserver)  # 連服務器
        smtp.login(sender, password)
    except:
        smtp = smtplib.SMTP_SSL(smtpserver, port)
        smtp.login(sender, password)  # 登錄
    smtp.sendmail(sender, receiver, msg.as_string())  # 發送
    smtp.quit()
    # #發送郵件
    # smtp = smtplib.SMTP()
    # smtp.connect('smtp.mxhichina.com')  # 郵箱服務器
    # smtp.login(username, password)  # 登錄郵箱
    # smtp.sendmail(sender, receiver, msg.as_string())  # 發送者和接收者
    # smtp.quit()
    print("郵件已發出!注意查收。")
# ======查找測試目錄,找到最新生成的測試報告文件======
def new_report(test_report):
    lists = os.listdir(test_report)  # 列出目錄的下所有文件和文件夾保存到lists
    lists.sort(key=lambda fn: os.path.getmtime(test_report + "\\" + fn))  # 按時間排序
    file_new = os.path.join(test_report, lists[-1])  # 獲取最新的文件保存到file_new
    print(file_new)
    return file_new
if __name__ == "__main__":
    # 返回實例
    runner = unittest.TextTestRunner()
    #導入第三方模塊HTMLTestRunner
    import HTMLTestReportCN
    import time
    # 獲取當前時間,這樣便於下面的使用。
    now = time.strftime("%Y-%m-%M-%H_%M_%S", time.localtime(time.time()))
    #保存生成報告的路徑
    report_path =  "C:\\Users\\DELL\\PycharmProjects\\honggetest\\report\\"+now+"_result.html"
    fp = open(report_path,'wb')
    runner = HTMLTestReportCN.HTMLTestRunner(stream=fp,
                                           title=u"這是我的自動化測試用例",
                                           description=u"用例執行情況",
                                           verbosity = 2
                                           )
    # run 所有用例
    runner.run(all_case())
    #關閉文件,記住用open()打開文件后一定要記得關閉它,否則會占用系統的可打開文件句柄數。
    fp.close()
    #測試報告文件夾
    test_path = "C:\\Users\\DELL\\PycharmProjects\\honggetest\\report\\"
    new_report = new_report(test_path)
    send_mail(new_report)  # 發送測試報告

小結

 1、第二處我注釋掉也可以發出去,兩個收件人可以收到郵件,但是如果這樣的話,公司郵箱收件人只顯示一個收件人,QQ郵箱顯示兩個收件人。

公司郵箱    PS:如果將紅色框上邊的注釋掉,下邊的不注釋,就可以看到兩個收件人的郵箱

 

 以下是個人愚見,如果不對請指出

from email.mime.text import MIMEText

from email.mime.multipart import MIMEMultipart

import smtplib

以上是導入的包,通過email和smtplib實現發郵件。

折騰好久,發現是這樣:email中收件人和sendmail中的收件人是沒啥聯系的。

mail_to = ['test1@exp.com','test2@exp.com']

server = smtplib.SMTP()

server.connect()

server.sendmail(mail_from, mail_to, msg.as_string())

server.quit()

mail_to = 'test1@exp.com,test2@exp.com'

msg = MIMEMultipart('related') ##采用related定義內嵌資源的郵件體

msgtext = MIMEText(content,_subtype='html',_charset='utf-8') ##_subtype有plain,html等格式,避免使用錯誤

msg['Subject'] = subject

msg['From'] = mail_from

msg['To'] =mail_to

sendmail中收件人,它的格式應該為list。這個為實際的收件人地址。

而msg['To'] 格式是字符串(str)。這個只是為了郵件中打印出來而已。

sendmail查源碼,python/lib/smtplib.py大概690行左右,或者搜索tolist。

2、在使用python添加附件發送時報錯:Cannot attach additional subparts to non-multipart/* 

查詢得知,錯誤的原因在於缺少這行代碼:

msg = MIMEMultipart() 

將這行加上:msg = MIMEMultipart() 即可

 郵件收不到的幾種原因

1、Subject 和正文內容不要用 hello、hehe、test 等單詞

2、from(發件人)和 to(收件人)不要為空,(要不然會被認為是垃圾郵件)

3、找不到的話,先看下垃圾信箱,是不是跑到垃圾箱了

4、如果前幾次可以收到,后來收不到了,需改下 subject 內容(因為每次都是一個 subject,系統也會拒收的,把 subject 內容設置為動態的是最好的)

5、部分郵箱是 ssl 加密了的,所以無法發送,如:qq 郵箱(用授權碼去登錄)

6、要是按照上面的步驟來報錯了,說明代碼抄錯了,多檢查幾次。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM