封装发送邮件的方法
class Email(object):
'''
更改email_attachment方法中的如下3项即可:
1、 sender:发件人的邮箱,为163邮箱;
2、 pwd:发送邮箱的密码
注意:此密码不是登录密码,而是网络授权码
3、 receiver: 收件人的邮箱
'''
def email_attachment(self,report_file):
'''配置发送附件测试报告到邮箱'''
'''发件相关参数'''
try:
# 发件服务器
smtpserver = 'smtp.163.com'
port = 25
sender = '*******@163.com'
psw = '******'
receiver = '******@qq.com'
msg = MIMEMultipart()
msg['from'] = sender
msg['to'] = ';'.join(receiver)
msg['subject'] = '这个是ranzhi项目自动化测试报告主题'
'''读取测试报告内容'''
with open(report_file, 'rb') as rp:
ranzhi_mail_body = rp.read()
'''正文'''
body = MIMEText(ranzhi_mail_body, 'html', 'utf8')
msg.attach(body)
'''附件'''
att = MIMEText(ranzhi_mail_body, 'base64', 'utf8')
att['Content-Type'] = 'application/octet-stream'
att['Content-Disposition'] = 'attachment;filename = "%s"' % report_file
msg.attach(att)
'''发送邮件'''
smtp = smtplib.SMTP()
smtp.connect(smtpserver, port)
smtp.login(sender, psw)
smtp.sendmail(sender, receiver.split(';'), msg.as_string()) # 发送
smtp.close()
print("邮件发送成功!")
except Exception as e:
print(e)
print("邮件发送失败!")