当前位置: 移动技术网 > IT编程>脚本编程>Python > 使用python将最新的测试报告以附件的形式发到指定邮箱

使用python将最新的测试报告以附件的形式发到指定邮箱

2019年09月20日  | 移动技术网IT编程  | 我要评论

恽小华,爱之方舟,麦泽利安

import smtplib, email, os, time
from email.mime.multipart import mimemultipart
from email.mime.text import mimetext
from email.header import header


#设置smtplib所需的参数
smtpserver = 'smtp.qq.com' #smtp服务器地址
username = 'xxx@qq.com' # 发件人地址,通过控制台创建的发件人地址
password = '******' # 发件人密码,通过控制台创建的发件人密码
receiver = ['xxx@dadaodata.com'] #单个收件人
# receivers = ['xxx@dadaodata.com', 'xxx@qq.com'] # 收件人地址或是地址列表,支持多个收件人,最多30个

# 构造邮件mimemultipart对象
msg = mimemultipart('mixed')
msg['subject'] = header('自动化测试报告' + time.strftime("%y-%m-%d"), 'utf-8').encode()#自定义邮件主题
msg['from'] = '%s <%s>' % (username, username)#邮件发送者
msg['to'] = ";".join(receiver)#邮件接受者
msg['message-id'] = email.utils.make_msgid()
msg['date'] = email.utils.formatdate()

# 构造文字内容
text_plain = mimetext('附件为接口自动化测试报告,请查收!', 'plain', 'utf-8')#邮件内容
msg.attach(text_plain)

#构造附件
test_report = r'f:\pythonautomation\python_pycharm\testreport' #存放文件的目录
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
sendfile = open(file_new,'rb').read()
text_att = mimetext(sendfile, 'base64', 'utf-8')
text_att["content-type"] = 'application/octet-stream'
text_att["content-disposition"] = 'attachment; filename="report.html"'#重新命名附件
msg.attach(text_att)

# 发送邮件
try:
# client = smtplib.smtp()
# client.connect(smtpserver, 25) #smtp普通端口为25
client = smtplib.smtp_ssl() #python 2.7以上版本,若需要可使用ssl
client.connect(smtpserver, 465) #ssl端口465
# client.set_debuglevel(1) #用set_debuglevel(1)可以打印出和smtp服务器交互的所有信息
client.login(username, password)
client.sendmail(username, receiver, msg.as_string())
client.quit()
print('邮件发送成功')
except smtplib.smtpconnecterror as e:
print('邮件发送失败,连接失败:', e.smtp_code, e.smtp_error)
except smtplib.smtpauthenticationerror as e:
print('邮件发送失败,认证错误:', e.smtp_code, e.smtp_error)
except smtplib.smtpsenderrefused as e:
print('邮件发送失败,发件人被拒绝:', e.smtp_code, e.smtp_error)
except smtplib.smtprecipientsrefused as e:
print('邮件发送失败,收件人被拒绝:', e.args, e.recipients)
except smtplib.smtpdataerror as e:
print('邮件发送失败,数据接收拒绝:', e.smtp_code, e.smtp_error)
except smtplib.smtpexception as e:
print('邮件发送失败: ', str(e))
except exception as e:
print('邮件发送失败: ', str(e))

执行结果如下:

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网