Python邮箱操作
Python对SMTP支持有smtplib和email两个模块,email负责构造邮件,smtplib负责发送邮件。这样就可以在脚本完成测试之后,将测试报告发送给相关的责任人。
- 以附件形式发送邮件
import smtplib,os
from email.mime.text import MIMEText
from email.header import Header
from email.mime.multipart import MIMEMultipart
#设置发送邮箱服务器
smptServer = 'smtp.163.com'
#设置发送邮箱用户、密码或授权码(163和QQ需要的是授权码不是密码)
user = '**********@163.com'
psword = '*******************'
#发送邮箱
sender = '**********@163.com'
#接收邮箱
receiver = '************@qq.com'
#发送文件主题
subject = 'python发送邮件'
#发送html格式的文件
#读取文件
path = os.getcwd() + '/2022-10-20-11—33—11.html'
#编写HTML类的邮箱正文
file = open('测试报告.html','rb')
f = file.read()
file.close()
msg = MIMEMultipart()
#实例化html文件
html_part = MIMEText(f,'base64','gb2312') #将html文件以附件的形式发送
html_part['Content-Type'] = 'application/octet-stream'
html_part.add_header('Content-Disposition', 'attachment', filename='2022-10-20-11—33—11.html')# filename是指下载的附件的命名
#绑定到message里
msg.attach(html_part)
msg['Subject'] = Header(subject,'utf-8')
msg['From'] = sender
msg['To'] = receiver
#创建发送邮箱服务对象
smtp = smtplib.SMTP()
#连接发送邮件服务器
smtp.connect(smptServer)
#登录邮箱,输入邮箱名,密码
smtp.login(user,psword )
#发送邮件
smtp.sendmail(sender,receiver,msg.as_string())
#关闭邮箱对象
smtp.quit()