自动发送邮件是自动化测试项目的重要需求之一。发送邮件的协议,是简单邮件传输协议(SMTP)。
1. Python自带的发送邮件功能
1.1 发送邮件正文
import smtplib
from email.mime.text import MIMEText
from email.header import Header
# 发送邮件主题
subject = 'Python email test'
# 编写HTML类型的邮件正文
msg = MIMEText('<html><h1>你好!</h1></html>', 'html', 'utf-8')
msg['Subject'] = Header(subject, 'utf-8')
# 发送邮件
smtp = smtplib.SMTP()
smtp.connect("smtp.qq.com")
smtp.login("sender@qq.com", "sendpassword")
smtp.sendmail("sender@qq.com", "receiver@qq.com", msg.as_string())
smtp.quit()
结果:
1.2 发送带附件的邮件
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# 邮件主题
subject = 'Python send email test'
# 发送的邮件
with open('log.txt', 'rb') as f:
send_att = f.read()
att = MIMEText(send_att, 'text', 'utf-8')
att["Content-Type"] = 'application/octet-stream'
att["Content-Disposition"] = 'attachment;filename="log.txt'
msg = MIMEMultipart()
msg['Subject'] = subject
msg.attach(att)
# 发送邮件
smtp = smtplib.SMTP()
smtp.connect("smtp.qq.com")
smtp.login("sender@qq.com", "senderpassword")
smtp.sendmail("sender@qq.com", "receiver@qq.com", msg.as_string())
smtp.quit()
结果:
2. 使用yagmail发送邮件
import yagmail
# 连接邮箱服务器
yag = yagmail.SMTP(user="sender@qq.com", password="senderpassword", host='smtp.qq.com')
# 邮件正文
contents = ['This is the body,and here is just text http://somedomain/image.png',
'You can find an audio file attached.']
# 发送邮件
yag.send("receiver1@qq.com", "subject", contents)
yag.send(["receiver1@qq.com","receiver2@126.com"],'subject',contents,["F:\python\AutoTest\\venv\\test8-数据驱动应用\\baidu_data.csv","F:\python\AutoTest\\venv\\test8-数据驱动应用\\ddt_data_file.json"])