1 # 发送html内容的邮件
2 import smtplib, time, os
3 from email.mime.text import MIMEText
4 from email.header import Header
5
6
7 def send_mail_html(file):
8 '''发送html内容邮件'''
9 # 发送邮箱
10 sender = 'zhangkai@192.168.20.190'
11 # 接收邮箱
12 receiver = 'gongxingrui@192.168.20.190'
13 # 发送邮件主题
14 t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
15 subject = '自动化测试结果_' + t
16 # 发送邮箱服务器
17 smtpserver = '192.168.20.190'
18 # 发送邮箱用户/密码
19 username = 'zhangkai'
20 password = '123456'
21
22 # 读取html文件内容
23 f = open(file, 'rb')
24 mail_body = f.read()
25 f.close()
26
27 # 组装邮件内容和标题,中文需参数‘utf-8’,单字节字符不需要
28 msg = MIMEText(mail_body, _subtype='html', _charset='utf-8')
29 msg['Subject'] = Header(subject, 'utf-8')
30 msg['From'] = sender
31 msg['To'] = receiver
32 # 登录并发送邮件
33 try:
34 smtp = smtplib.SMTP()
35 smtp.connect(smtpserver)
36 smtp.login(username, password)
37 smtp.sendmail(sender, receiver, msg.as_string())
38 except:
39 print("邮件发送失败!")
40 else:
41 print("邮件发送成功!")
42 finally:
43 smtp.quit()
44
45
46 def find_new_file(dir):
47 '''查找目录下最新的文件'''
48 file_lists = os.listdir(dir)
49 file_lists.sort(key=lambda fn: os.path.getmtime(dir + "\\" + fn)
50 if not os.path.isdir(dir + "\\" + fn)
51 else 0)
52 # print('最新的文件为: ' + file_lists[-1])
53 file = os.path.join(dir, file_lists[-1])
54 print('完整文件路径:', file)
55 return file
56
57
58 dir = 'D:\\test_data\\auto_test_result' # 指定文件目录
59 file = find_new_file(dir) # 查找最新的html文件
60 send_mail_html(file) # 发送html内容邮件