1. 发送带附件的邮件
- MIMEMultipart 可以构造带附件的邮件
1 import smtplib 2 from email.mime.text import MIMEText 3 from email.mime.multipart import MIMEMultipart # 构造带附件的邮件 4 5 # 发送邮箱服务器、用户、密码 6 smtpserver = 'smtp.qq.com' 7 user = '123456789' 8 passwd = 'fjkdajfkda' 9 10 # 发送邮箱、接收邮箱 11 sender = '[email protected]' 12 receiver = '[email protected],[email protected]' 13 14 # 主题、发送的附件 15 subject = 'test带附件' 16 sendfile = open(r'D:\zhangyang\PycharmProjects\test2\testresult2020-03-31 16_22_18.html', 'rb').read() 17 18 att = MIMEText(sendfile, 'html', 'utf-8') 19 att["Content-Type"] = 'application/octet-stream' 20 att["Content-Disposition"] = 'attachment; filename="testresult2020-03-31 16_22_18.html"' 21 22 msgRoot = MIMEMultipart('related') 23 msgRoot['Subject'] = subject 24 msgRoot.attach(att) 25 26 # 连接并发送邮件 27 smtp = smtplib.SMTP() 28 smtp.connect(smtpserver) 29 smtp.login(user, passwd) 30 smtp.sendmail(sender, receiver.split(','), msgRoot.as_string()) 31 smtp.quit()
2. 查找最新报告
1 import os 2 3 result_dir = r'D:\zhangyang\PycharmProjects\test2' # 定义测试报告的目录 4 lists = os.listdir(result_dir) # 获取目录下的所有文件及文件夹 5 6 lists.sort(key=lambda fn: os.path.getmtime(result_dir+"\\"+fn)) # 按时间排序 7 print('最新的文件为:' + lists[-1]) 8 file = os.path.join(result_dir, lists[-1]) # 取到最新的文件或文件夹 9 print(file)