测试报告发送到邮箱:利用python的email和smtp模块发送到QQ邮箱(普通文本,html,附件形式)
本文从几个标题阐述问题:
1 发送邮件的基本流程
2 如何获取授权码
3 编写代码发送普通文本plain到邮件
4 编写代码发送html到邮件
5 编写代码发送附件到邮件
6 关于发件者和收件者的名字显示和自己代码不一致的问题
1 发送邮件的基本流程
以QQ邮箱为例子:
(1)知晓QQ邮箱的地址。即IP+端口port: server_ip = "smtp.qq.com", server_port = "465"
(2)登陆QQ邮箱。输入用户名和密码,在这里由于授权码的缘故,密码填写授权码而不是密码。
(3)确定发件人和收件人。收件人如果是列表,代表群发。
(4)确定发邮件的主题和内容。
2 获取授权码
(1)进入QQ邮箱----点击设置----如下位置开启服务
(2)根据提示发送短信
(3)接收授权码妥善保存,不要让别人知道
3 编写代码发送普通文本plain到邮件
SMTP是发送邮件的协议,Python内置对SMTP的支持,可以发送纯文本邮件、HTML邮件以及带附件的邮件。
Python对SMTP支持有smtplib和email两个模块,email负责构造邮件,smtplib负责发送邮件。
SMTP协议就是简单的文本命令和响应。
set_debuglevel(1)就可以打印出和SMTP服务器交互的所有信息。
login()方法用来登录SMTP服务器。
sendmail()方法就是发邮件,由于可以一次发给多个人,所以传入一个list。
邮件正文是一个str,as_string()把MIMEText对象变成str。
# coding=utf-8 import time import smtplib from email.mime.text import MIMEText from email.header import Header def sendEmail(serverip, serverport, username, password, from_addr, to_addr, subject, content): msg = MIMEText(content, _subtype='plain', _charset='utf-8') msg['Subject'] = Header(subject, 'utf-8') msg['From'] = from_addr msg['To'] = ','.join(to_addr) try: server = smtplib.SMTP_SSL(serverip, serverport) server.set_debuglevel(1) server.login(username, password) server.sendmail(from_addr, to_addr, msg.as_string()) print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) except Exception as err: print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) print(err) server.quit() if __name__ == '__main__': # 邮件服务器的地址 server_ip = "smtp.qq.com" server_port = "465" # 用户登陆,需要你自己的邮箱授予的授权码填写到密码部分,不是QQ邮箱密码 username = "xxxxx@qq.com" password = "yyyyy" # 发送人和接收人,接收人是列表,则表示群发 from_addr = "xxxxx@qq.com" to_list = ['xxxxxx@qq.com', 'xxxxx@qq.com'] # 发送的主题和内容,本次测试针对plain类型,即普通文本,非html和附件发送 subject = '自动化测试unittest测试框架报告:' content = "Hello World" sendEmail(server_ip, server_port, username, password, from_addr, to_list, subject, content)
根据你自己的邮箱和授权码替换掉上面代码,确认无误就可以收到邮件了。
4 编写代码发送html到邮件
(1)把上面代码的_subtype='plain'替换成'html'
(2)把上面content的内容替换成
with open("hello.html", 'rb') as f: content = f.read()
(3)html的内容如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <h1 style="color: #006699">Hello World</h1> </body> </html>
5 编写代码发送附件到邮件
如果要携带附件你需要清楚你携带附件(attachment)的MIME信息。
(1)要建立一个MIMEMultipart()对象
(2)要把一本文本和附件对象添加到这个对象里去
代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# coding=utf-8 import time import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header def sendEmail(serverip, serverport, username, password, from_addr, to_addr, subject, content): msg = MIMEMultipart() msg['Subject'] = Header(subject, 'utf-8') msg['From'] = from_addr msg['To'] = ','.join(to_addr) # 对象添加一般文本内容 msg.attach(MIMEText(content, _subtype='plain', _charset='utf-8')) # 对象添加附件test.txt with open('test.txt', 'rb') as f: text = f.read() attachment_file = MIMEText(text, 'base64', 'utf-8') attachment_file["Content-Type"] = 'application/octet-stream' attachment_file["Content-Disposition"] = 'attachment; filename="test.txt"' msg.attach(attachment_file) try: server = smtplib.SMTP_SSL(serverip, serverport) server.set_debuglevel(1) server.login(username, password) server.sendmail(from_addr, to_addr, msg.as_string()) print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) except Exception as err: print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) print(err) server.quit() if __name__ == '__main__': server_ip = "smtp.qq.com" server_port = "465" username = "xxxxx@qq.com" password = "yyyyyy" from_addr = "xxxxx@qq.com" to_list = ['xxxxx@qq.com', 'xxxxx@qq.com'] subject = '自动化测试unittest测试框架报告:' content = "Hello World" sendEmail(server_ip, server_port, username, password, from_addr, to_list, subject, content)
6 关于发件者和收件者的名字显示和自己代码不一致的问题
很多时候无法自定义发送者和接收者的字符串,因为很多邮件服务商在显示邮件时,比如发件人和收件人都是QQ邮箱用户
会把发件人,收件人名字自动替换为用户注册的名字,但是其他收件人名字的显示不受影响。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
# coding=utf-8 import time import smtplib from email.mime.text import MIMEText from email.header import Header from email.utils import parseaddr, formataddr def _format_addr(s): name, addr = parseaddr(s) return formataddr((Header(name, 'utf-8').encode(), addr.encode('utf-8') if isinstance(addr, unicode) else addr)) def sendEmail(serverip, serverport, username, password, from_addr, to_addr, subject, content): msg = MIMEText(content, _subtype='plain', _charset='utf-8') msg['Subject'] = Header(subject, 'utf-8') # msg['From'] = from_addr # msg['To'] = ','.join(to_addr) # 很多时候无法自定义发送者和接收者的字符串,因为很多邮件服务商在显示邮件时,比如发件人和收件人都是QQ邮箱用户 # 会把发件人,收件人名字自动替换为用户注册的名字,但是其他收件人名字的显示不受影响。 msg['From'] = str(Header("邮件发送者", 'utf-8')) msg['To'] = str(Header("邮件接收者", 'utf-8')) try: server = smtplib.SMTP_SSL(serverip, serverport) server.set_debuglevel(1) server.login(username, password) server.sendmail(from_addr, to_addr, msg.as_string()) print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) except Exception as err: print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) print(err) server.quit() if __name__ == '__main__': # 邮件服务器的地址 server_ip = "smtp.qq.com" server_port = "465" # 用户登陆,需要你自己的邮箱授予的授权码填写到密码部分,不是QQ邮箱密码 username = "1224314791@qq.com" password = "zeecftlzfzfxgjhh" # 发送人和接收人,接收人是列表,则表示群发 from_addr = "1224314791@qq.com" to_addr_list = ['1224314791@qq.com', '1224314791@qq.com'] # 发送的主题和内容,本次测试针对plain类型,即普通文本,非html和附件发送 subject = '自动化测试unittest测试框架报告:' content = "Hello World" sendEmail(server_ip, server_port, username, password, from_addr, to_addr_list, subject, content)