- pip3 install PyEmail #smtplib 邮件发送
import notifiers
import smtplib
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from app.Handler import *
class SendEmail:
def __init__(self):
self.send_user = 'sales@xxx' # 发送邮件的用户
self.email_host = 'smtpdm.aliyun.com' # SMTP 服务器地址:smtp.qq.com
self.email_port = 465 # 服务器端口 465
self.password = 'xxxx' # 开启POP3/SMTP服务,在第三方客户端登录时,生成的授权码
def send_notifiers(self):
email = notifiers.get_notifier('email')
params = {
"username": "sales@xxxx", # 邮件发送邮箱用户名
"password": "xxxx", # 邮件发送邮箱密码
"ssl": True, # 是否启用tls(默认不启用)
"from": "sales@xxxx", # 发件地址
"to": ["13149992@qq.com"], # 收件地址,可以执行多个收件地址
"host": "smtpdm.aliyun.com", # 邮件服务器地址
"port": 465, # 邮件服务器端口
"subject": "Python系统接口错误报警" # 邮件主题
}
email.notify(message="这是一封测试邮件,请忽略", **params)
print('发送成功')
def send_email_a(self, title, data, user_list, email_type='html', file_path_list=[]):
try:
message = MIMEText(data, _subtype='plain', _charset='utf-8')
if len(file_path_list) > 0:
message = MIMEMultipart()
if email_type == 'html':
message = MIMEMultipart('related')
content = MIMEText(data, 'html', 'utf-8')
message.attach(content)
file = open(f'{Config.APP_URL}/email.png', "rb")
img_data = file.read()
file.close()
img = MIMEImage(img_data)
img.add_header('Content-ID', 'image')
message.attach(img)
message['Subject'] = title
message['From'] = self.send_user
message['To'] = ";".join(user_list)
for file_path in file_path_list:
# 构造附件
attrs = MIMEText(open(file_path, 'rb').read(), 'base64', 'utf-8')
attrs["Content-Type"] = 'application/octet-stream'
attrs["Content-Disposition"] = 'attachment; filename={}'.format(str(file_path).split('/')[-1]) # 这里的filename可以任意写,写什么名字,邮件中显示什么名字
message.attach(attrs)
server = smtplib.SMTP_SSL(self.email_host)
server.connect(self.email_host, self.email_port)
server.login(self.send_user, self.password)
server.sendmail(self.send_user, user_list, message.as_string())
server.close()
print("发送邮件成功,请查收")
except Exception as e:
print("发送邮件失败,报错信息:", e)
if __name__ == "__main__":
# SendEmail().send_notifiers()
user_list = ["13149992@qq.com"]
title = "邮件标题"
data = "邮件文本内容"
data = """
<p>全是BUG</p>
<p><a href="https://www.cnblogs.com/">qf</a></p>
<p>图片演示:</p>
<p><img src="cid:image"></p>
"""
file_path_list = [f'{Config.APP_URL}/email.png']
SendEmail().send_email_a(title=title, data=data, user_list=user_list, email_type='html', file_path_list=file_path_list)