Python+selenium整合自动发邮件功能

主要实现的目的是:自动将测试报告以邮件的形式通知相关人员

 from HTMLTestRunner import HTMLTestRunner
import HTMLTestReport
from email.mime.text import MIMEText
from email.header import Header
import smtplib
import unittest
import time
import os # ******************定义发送邮件******************
def send_mail(file_new):
f = open (file_new, 'rb')
filename = f.read ()
f.close ()
smtp = smtplib.SMTP ()
smtp.connect ('smtp.163.com')
sender = 'fengyiru6369@163.com'
receiver = '1194150169@qq.com'
username = 'fengyiru6369@163.com'
password = 'FYRu19200915'
smtp.login (username, password) subject = '附件为最新测试报告,望查收'
msg = MIMEText (filename, 'html', 'utf-8')
msg['Subject'] = Header("自动化测试报告",'utf-8')
msg['From'] = 'Tim<fengyiru6369@163.com>'
msg['To'] = '1194150169@qq.com'
smtp.sendmail (sender, receiver, 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))
file_new = os.path.join (testreport, lists[-1])
print (file_new)
return file_new if __name__ == "__main__":
test_dir = r'E:\python\测试报告'
test_report = r'E:\python\测试报告'
discover = unittest.defaultTestLoader.discover (test_dir, pattern='testreport1.py')
now = time.strftime ("%Y-%m-%d_%H_%M_%S")
filename1 = test_report + '\\' + now + 'result.html'
fp = open (filename1, 'wb')
# runner = HTMLTestReport.HTMLTestRunner (stream=fp, title=u"自动化测试报告", description='自动化测试演示报告', tester='fyr')
runner = HTMLTestRunner (stream=fp, title='集成测试报告', description='测试用例执行情况')
runner.run (discover)
fp.close ()
new_report = new_report (test_report)
print(new_report)
send_mail (new_report) # 发送测试包

该程序的执行过程分为三个步骤:

1.通过unittest框架的discover()找到匹配的测试用例,由HTMLTestRunner的run()方法执行测试用例并生成最新的测试报告。

2.调用new_report()函数找到测试报告目录找到测试报告目录(report)下最新的测试报告,返回测试报告的测试报告的路径。

3.将得到的最新测试报告的完整路径传给send_mail()函数,实现发送邮件功能。

上一篇:codegate-quals-2013-vuln100


下一篇:java实现后台自动发邮件功能