python发邮件须要掌握两个模块的用法,smtplib和email,这俩模块是python自带的,只需import便可使用。smtplib模块主要负责发送邮件,email模块主要负责构造邮件。html
smtplib模块主要负责发送邮件:是一个发送邮件的动做,链接邮箱服务器,登陆邮箱,发送邮件(有发件人,收信人,邮件内容)。python
email模块主要负责构造邮件:指的是邮箱页面显示的一些构造,如发件人,收件人,主题,正文,附件等。api
import smtplib smtp = smtplib.SMTP() smtp.connect('smtp.163.com,25') smtp.login(username, password) smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit()
from email.mime.text import MIMEText from email.header import Header from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart
咱们必须把Subject,From,To添加到MIMEText对象或者MIMEMultipart对象中,邮件中才会显示主题,发件人,收件人。服务器
# 组装邮件内容和标题,中文需参数‘utf-8’,单字节字符不须要 msg = MIMEMultipart() msg['Subject'] = Header(subject) msg['From'] = sender msg['To'] = ','.join(user_list)
自动化测试报告为HTML,以附件方式发送,并发
无论什么类型的附件,均可以用MIMEApplication,MIMEApplication默认子类型是application/octet-streamapp
# 发送html内容的邮件 import smtplib import time import os from email.mime.text import MIMEText from email.header import Header from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart class SendMail(): def find_new_file(self, dir): '''查找目录下最新的文件''' file_lists = os.listdir(dir) file_lists.sort(key=lambda fn: os.path.getmtime(dir + "\\" + fn) if not os.path.isdir(dir + "\\" + fn) else 0) # print('最新的文件为: ' + file_lists[-1]) file = os.path.join(dir, file_lists[-1]) print('完整文件路径:', file) return file def send_mail_html(self, file): '''发送html格式测试报告邮件''' # 发送邮箱 sender = 'name@163.com' # 接收邮箱 user_list = [ 'user@foxmail.com', 'user@qq.com', 'user@qq.com'] # 发送邮件主题 t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) subject = '接口自动化测试结果(请下载附件查看)_' + t # 发送邮箱服务器 smtpserver = 'smtp.163.com' # 发送邮箱用户/密码 username = 'user@163.com' password = 'youer_password' # 组装邮件内容和标题,中文需参数‘utf-8’,单字节字符不须要 msg = MIMEMultipart() msg['Subject'] = Header(subject) msg['From'] = sender msg['To'] = ','.join(user_list) # ---这是附件部分--- # html类型附件,无论什么类型的附件,均可以用MIMEApplication,MIMEApplication默认子类型是application/octet-stream。 part = MIMEApplication(open(file, 'rb').read()) part.add_header('Content-Disposition', 'attachment', filename=file) msg.attach(part) # 登陆并发送邮件 try: smtp = smtplib.SMTP() smtp.connect(smtpserver) smtp.login(username, password) smtp.sendmail(sender, user_list, msg.as_string()) except BaseException: print("邮件发送失败!") else: print("邮件发送成功!") finally: smtp.quit() if __name__ == '__main__': sen = SendMail() dir = r'D:\\api\\report' # 指定文件目录 b = sen.find_new_file(dir) # 查找最新的html文件 sen.send_mail_html(b) # 发送html内容邮件
ps:函数
python邮件发送给多人时,只有第一我的能收到的问题,测试
MIMEText()["to"]的数据类型与sendmail(from_addrs,to_addrs,...)的to_addrs不一样;前者为str类型,多个地址使用逗号分隔,后者为list类型。ui
expects toaddrs to be a list of email addresses. (Or, of course, just use recipients in place of toaddrs.)
参考连接:https://stackoverflow.com/questions/20509427/python-not-sending-email-to-multiple-addressesspa