smtp發(fā)送郵件用法
1發(fā)送郵件def:
python登錄qq賬號佩捞, 屬于第三方登錄复哆, 密碼需寫SMTP服務 驗證碼掂骏,不輸入真實qq密碼
2.最新報告def:
3.運行:
4.具體代碼:
# coding:utf-8
import unittest
import os
import HTMLTestRunner
import time
import smtplib
from email.mime.multipartimport MIMEMultipart
from email.mime.textimport MIMEText
from email.headerimport? Header
import datetime
now = time.strftime("%Y-%m-%d %H_%M_%S")
# 用例路徑
case_path = os.path.join(os.getcwd(), "testcase")
#報告存放文件夾路徑
test_report ="D:\\pythonproject\\Autotest\\report"
# 報告存放路徑
report_path = os.path.join(os.getcwd(), "D:\\pythonproject\\Autotest\\report\\"+now+"report.html")
##用例集
def all_case():
discover = unittest.defaultTestLoader.discover(case_path,
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? pattern="test*.py",
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? top_level_dir=None)
print(discover)
return discover
##發(fā)送郵件
def send_mail(file_new):
f=open(file_new,'rb')
mail_body =f.read()
f.close()
msg = MIMEMultipart()
#msg = MIMEText(mail_body,_subtype='html',_charset='utf8')
? ? msg['From'] ='1020474486@qq.com'
? ? msg['To'] ='1459581689@qq.com'
? ? msg['subject'] = Header('測試結果(' +str(datetime.date.today()) +')','utf-8')
att = MIMEText(open(report_path, 'rb').read(), 'base64', 'gb2312')
att["Content-Type"] ='application/octet-stream'
? ? att["Content-Disposition"] ='attachment; filename="testTemplate.html"'
? ? msg.attach(att)
body ="Python test mail"
? ? msg.attach(MIMEText(body, 'plain'))
smtp= smtplib.SMTP()
smtp.connect('smtp.qq.com')
smtp.login('1020474486','XXXXXXXXXXX')
smtp.sendmail('1020474486@qq.com','1459581689@qq.com',msg.as_string())
smtp.quit()
print('email has send out!')
#####查找測試報告目錄焕毫, 找到最新生成的測試報告文件+======
def new_report(testreport):
lists = os.listdir(testreport)
lists.sort(key=lambda? fn:os.path.getmtime(testreport+"\\"+fn))
print(('最新文件為:'+ lists[-1]))
file = os.path.join(testreport,lists[-1])
print(file)
return (file)
if __name__ =='__main__':
##生成報告
? ? fp =open(report_path,"wb")
runner = HTMLTestRunner.HTMLTestRunner(stream=fp, title='這是我的自動化測試報告', description='用例執(zhí)行情況:')
##執(zhí)行所有用例
? ? runner.run(all_case())
fp.close()
new_report =new_report(test_report)
print("hehe"+ new_report)
send_mail(new_report)