Python-自动发送各种类型附件的邮件
发送邮件的基本思路就是使用MIMEMultipart来组装(attach)各个部分:邮件主题,邮件发送者,邮件接收者,邮件正文以及附件等等,其中附件需要add_header加入附件声明
继承关系如下:
MIMEBase
--MIMENonMultipart
--MIMEApplication
--MIMEAudio
--MIMEImage
--MIMEMessage
--MIMEText
--MIMEMultipart
一般来说,不会直接使用到MIMEBase类,而是直接使用它的继承类。MIMEMultipart有attach方法,而MIMENonMultipart没有,只能被attach,MIME有很多种类型,而最终只提供(音频: MIMEAudio;图片: MIMEImage; 文本:MIMEText),如果是其它类型,如word,excel,html就不知道该用哪种类型
作者的附件类型是HTML,使用MIMIText一直不尽如人意,如下图:
针对以上问题解决方案:
不管什么类型的附件,都用MIMEApplication,它的默认子类型是application/octet-stream(二进制文件),客户端比如qq邮箱,收到这个声明后,会根据扩展名来猜测
贴作者代码:
#coding: utf-8
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.mime.application import MIMEApplication
import time
from project_prctice.common import dir_config as Dir
import os
from project_prctice.common.logger import FrameLog as log
class SendMail:
def __init__(self):
self.file = self.find_newest_file()
def find_newest_file(self):
'''
查找目录下最新的文件
:return:
'''
file_list = os.listdir(Dir.reports_dir)
file_list.sort()
filepath = os.path.join(Dir.reports_dir, file_list[-2]) #因该文件夹下有__init__文件,因此为固定输出结果
return filepath
def send_mail_html(self):
'''
发送html内容邮件
:param file:
:return:
'''
msg = MIMEMultipart()
#邮箱服务器
smtpserver = "smtp.qq.com"
#发送邮箱地址
msg_from = "****@qq.com"
# 发送方邮箱授权码
password = "rdtghsmihar"
#接收邮箱
msg_to= "****@qq.com"
#发送邮件主题
t = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
subject = "自动化测试报告_" + t #主题
content = "系统自动发出邮件,请勿回复" #邮件正文内容
msg.attach(MIMEText(content, 'plain', 'utf-8')) #实例化一个MIMEText邮件对象,该对象需要写进三个参数,分别是邮件正文,文本格式和编码
msg['Subject'] = Header(subject,'utf-8')
msg['From'] = msg_from
msg['To'] = msg_to
#---这是附件部分-----
#xlsx类型附件
# attachment = MIMEApplication(open('file.xlsx', 'rb').read())
# attachment.add_header('Content-Disposition', 'attachment', filename='file.xlsx')
# msg.attach(attachment)
#jpg类型附件
# attachment = MIMEApplication(open('file.jpg', 'rb').read())
# attachment.add_header('Content-Disposition', 'attachment', filename='file.jpg')
# msg.attach(attachment)
#mp4类型附件
# attachment = MIMEApplication(open('file.mp4', 'rb').read())
# attachment.add_header('Content-Disposition', 'attachment', filename='file.mp4')
# msg.attach(attachment)
#HTML附件
attachment = MIMEApplication(open(self.file, 'rb').read())
attachment.add_header('Content-Disposition','attachment',filename ='自动化测试报告.html')
msg.attach(attachment)
#登录并发送邮件
try:
smtp = smtplib.SMTP_SSL(smtpserver,smtplib.SMTP_SSL_PORT)
log().getLogger().info(f"{smtp}连接成功")
smtp.login(msg_from, password)
log().getLogger().info(f"{smtp}登陆成功")
smtp.sendmail(msg_from, msg_to, msg.as_string())
log().getLogger().info(f"{smtp}发送邮件成功")
smtp.quit()
except smtplib.SMTPException as e:
log().getLogger().error("发送邮件失败")
if __name__ == '__main__':
SendMail().send_mail_html()
效果如下图:
三十六般武艺,七十二般变化,修练出个人品牌并发出光芒
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律