"""
@Create time : 2023/4/15 15:29
@Functions :
@author : Lx
"""
import smtplib
from smtplib import SMTP_SSL
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
import os.path as osp
import warnings
class AutoEmail:
"""
支持发送: txt,log,csv,xlsx,jpg,png,py,文本内容, html文本
功能:自动根据文件后缀调用对应的处理方法;如果不是文件,则自动使用文本发送
"""
def __init__(self,
host_server='smtp.qq.com',
sender_qq='xxx@qq.com',
pwd='xxx',
receiver='xxx@qq.com',
mail_title='项目运行日志'):
self.host_server = host_server # qq邮箱smtp服务器
self.sender_qq = sender_qq # 发件人邮箱
self.pwd = pwd # 授权码
self.receiver = receiver # 接受者
self.mail_title = mail_title # 邮件标题
self.reset_sources()
self.img_count = 0
def addpng(self, file):
# 附件图像png
with open(file, 'rb') as f:
attachment = MIMEImage(f.read())
attachment.add_header('Content-ID', 'imageid')
show_name = osp.basename(file)
attachment.add_header('Content-Disposition', 'attachment',
filename=Header(show_name, 'utf-8').encode())
self.msg.attach(attachment)
# 将图片添加到正文
self.addinnerimage(file)
self.img_count += 1
def addjpg(self, file):
self.addpng(file)
def addtxt(self, file):
# 附件txt文件
with open(file, 'rb') as f:
attachment = MIMEText(f.read(), 'base64', 'utf-8')
attachment["Content-Type"] = 'application/octet-stream'
show_name = osp.basename(file)
attachment.add_header('Content-Disposition', 'attachment',
filename=Header(show_name, 'utf-8').encode())
self.msg.attach(attachment)
def addpy(self, file):
self.addtxt(file)
def addcsv(self, file):
# 附件csv
with open(file, 'rb') as f:
attachment = MIMEText(f.read(), 'base64', 'utf-8')
show_name = osp.basename(file)
attachment.add_header('Content-Disposition', 'attachment',
filename=Header(show_name, 'utf-8').encode())
self.msg.attach(attachment)
def addlog(self, file):
# 附件log文件
with open(file, 'rb') as f:
attachment = MIMEText(f.read(), 'base64', 'utf-8')
attachment["Content-Type"] = 'application/octet-stream'
show_name = osp.basename(file)
attachment.add_header('Content-Disposition', 'attachment',
filename=Header(show_name, 'utf-8').encode())
self.msg.attach(attachment)
def addxlsx(self, file):
# 附件xslx
with open(file, 'rb') as f:
attachment = MIMEApplication(f.read()) # 文件
show_name = osp.basename(file)
attachment.add_header('Content-Disposition', 'attachment',
filename=Header(show_name, 'utf-8').encode())
self.msg.attach(attachment) # 添加附件到邮件
def addcontext(self, context):
# 普通文本内容
self.msg.attach(MIMEText(context + '\n', 'plain', 'utf-8'))
def addHtmlContext(self, context):
# 带html的信息
self.msg.attach(MIMEText(context, 'html', 'utf-8'))
def addinnerimage(self, file, txt=''):
txt = txt or file
imgbody = f'''
<h3>{txt}</h3>
<img src="cid:image{self.img_count}"/>
'''
msgtext = MIMEText(imgbody, "html", "utf-8")
self.msg.attach(msgtext)
with open(file, "rb") as f:
img = MIMEImage(f.read())
img.add_header("Content-ID", f"<image{self.img_count}>")
self.msg.attach(img)
def reset_sources(self, srcs=[]):
self.resource = srcs
self.msg = MIMEMultipart()
self.msg["Subject"] = Header(self.mail_title, 'utf-8')
self.msg["From"] = self.sender_qq
self.msg["To"] = Header("测试邮箱", "utf-8")
def send(self):
exist_files = []
contexts = []
for file in self.resource:
if not osp.exists(file):
contexts.append(file)
print(f'({file}) 将会以文本形式添加。')
else:
exist_files.append(file)
# 文本数据
for c in contexts:
self.addcontext(c)
# 文件数据(附件)
for file in exist_files:
recall_func = getattr(self, f'add{file.split(".")[-1]}', None)
if callable(recall_func):
recall_func(file)
else:
warnings.warn(f'处理{file}文件出现问题!')
# 发送数据
try:
smtp = SMTP_SSL(self.host_server) # ssl登录连接到邮件服务器
smtp.set_debuglevel(1) # 0是关闭,1是开启debug
_ = smtp.ehlo(self.host_server) # 跟服务器打招呼,告诉它我们准备连接,最好加上这行代码
_ = smtp.login(self.sender_qq, self.pwd)
_ = smtp.sendmail(self.sender_qq, self.receiver, self.msg.as_string())
_ = smtp.quit()
print("邮件发送成功")
except smtplib.SMTPException:
print("无法发送邮件")
if __name__ == '__main__':
ae = AutoEmail()
ae.reset_sources(['./test.csv', './test.xlsx', 'test.jpg',
'笔记.txt', './Records/tmp/val_results.png',
'测试代码', 'get_flops.py'
])
ae.send()
参考:(139条消息) Python实现自动发送邮件(详解)_msg.as_string()_小小白学计算机的博客-CSDN博客