上一篇,咱們雖然已經將生成的最新的測試報告發出去了,可是MIMEText 只能發送正文,沒法帶附件,所以我還須要繼續改造咱們的代碼,實現能夠發送帶有附件的郵件。發送帶附件的須要導入另一個模塊 MIMEMultipart。還有就是測html
試負責人不止一我的,須要將測試報告發給多我的,也就是多個收件人。這篇主要是圍繞這兩個主題進行講解的。python
一、導入模塊 MIMEMultipart服務器
from email.mime.multipart import MIMEMultipart
二、先讀取要發送文件的內容,file_new 是測試報告路徑的參數名app
三、下圖紅色框框 file_name 參數是發送的附件從新命名學習
四、file_new 是測試報告路徑的參數名,發送郵件是將其傳入測試
五、運行結果ui
六、查看收件箱編碼
上面都是發給一個收件人,那麼如何一次發給多個收件人呢?實際上是很是簡單的,只需改兩個小地方,便可,從這裏就能夠看出python的強大之處。
一、源碼加密
二、仿造修改spa
三、運行結果
四、收件箱查看
公司郵箱
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) # 發送測試報告
一、第二處我註釋掉也能夠發出去,兩個收件人能夠收到郵件,可是若是這樣的話,公司郵箱收件人只顯示一個收件人,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。
二、在使用python添加附件發送時報錯:Cannot attach additional subparts to non-multipart/*
查詢得知,錯誤的緣由在於缺乏這行代碼:
msg = MIMEMultipart()
將這行加上:msg = MIMEMultipart() 便可
一、Subject 和正文內容不要用 hello、hehe、test 等單詞
二、from(發件人)和 to(收件人)不要爲空,(要否則會被認爲是垃圾郵件)
三、找不到的話,先看下垃圾信箱,是否是跑到垃圾箱了
四、若是前幾回能夠收到,後來收不到了,需改下 subject 內容(由於每次都是一個 subject,系統也會拒收的,把 subject 內容設置爲動態的是最好的)
五、部分郵箱是 ssl 加密了的,因此沒法發送,如:qq 郵箱(用受權碼去登陸)
六、要是按照上面的步驟來報錯了,說明代碼抄錯了,多檢查幾回。
原文出處:https://www.cnblogs.com/du-hong/p/10819199.html