利用selenium自动化测试时往往需要将测试结果通过邮件形式发给相关人;这样就不用实时盯着测试的什么时候完成,测试完成后会将测试报告通过邮件通知相关人
以下是相关的代码:
#coding=utf-8
import smtplib
from email.mime.text import MIMEText
from email.header import Header
#发送邮箱
sender = 'xxxxxxxxx@xiaozhou.biz'
#接收邮箱
receiver = 'xxxxxxx@qq.com'
#发送邮件主题
subject = '放假通知'
#发送邮箱服务器
smtpserver = 'smtp.exmail.qq.com'
#发送邮箱用户/密码
username = 'xxxxxxxx@xiaozhou.biz'
password = 'xxxxxxxx'
msg = MIMEText('你好!','plain','utf-8')
msg['Subject'] = Header(subject, 'utf-8')
msg['From']='xxxxxxxx@xiaozhou.biz'
msg['To']='xxxxxxxxx@qq.com'
smtp = smtplib.SMTP()
smtp.connect('smtp.exmail.qq.com')
smtp.login(username, password)
smtp.sendmail(sender, receiver, msg.as_string())
smtp.quit()
主要注意以下几点:
1.如果代码没有没有msg['From']和msg['To']或是没有给这两个赋值,执行时会报'504'错误
2.MIMEText初始化的时候,中文的第二个参数要用'plain',用'text',中文就显示不出来
3.如果报'535'错误,需要检查下代码中配置SMTP服务器是否一致、邮箱用户名、密码是否正确;用到网易邮箱需要在邮箱中配置下客户端授权码,同时将密码改成授权码即可。