Python(1)自动发送邮件
python发邮件需要掌握两个模块的用法,smtplib和email,这俩模块是python自带的,只需import即可使用。smtplib模块主要负责发送邮件,email模块主要负责构造邮件。
smtplib模块主要负责发送邮件:是一个发送邮件的动作,连接邮箱服务器,登录邮箱,发送邮件(有发件人,收信人,邮件内容)。
email模块主要负责构造邮件:指的是邮箱页面显示的一些构造,如发件人,收件人,主题,正文,附件等。
1.smtplib模块
import smtplib smtp = smtplib.SMTP() smtp.connect('smtp.163.com,25') smtp.login(username, password) smtp.sendmail(sender, receiver, msg.as_string()) smtp.quit()
2.email模块
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)
3.编写发件函数,方便调用
自动化测试报告为HTML,以附件方式发送,
不管什么类型的附件,都可以用MIMEApplication,MIMEApplication默认子类型是application/octet-stream
# 发送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类型。
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-addresses
但行好事,莫问前程
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了