有时候通过python运行程序,在出现异常时,需要进行邮件通知,可能还需要截图。比如对浏览器进行控制时出现了异常,则需要进行截图分析。
email-validator 2.0.0.post2
import asyncio
import logging
import smtplib
import traceback
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.image import MIMEImage
# 配置日志记录器
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
async def email_notification(header: str = "默认标题",
message: str = "默认消息",
image_paths: list | None = None,
receiver: str = 'xxxxxxxxx@qq.com'):
"""
发送邮件通知,包含多张图片和文字说明
"""
try:
MAIL = {
"from": 'yyyyyyyyyy@qq.com',
"pwd": 'zzzzzzzzzzz',
"smtp": 'smtp.qq.com',
"port": 465 # 使用SSL端口为465,非SSL端口为25
}
msg = MIMEMultipart('related')
msg['Subject'] = Header(header, 'utf-8') # 标题
msg['From'] = MAIL['from'] # 发件人
msg['To'] = receiver # 收件人
# 创建邮件正文
html_content = f'<p>{message}</p>'
if image_paths:
for i, image_path in enumerate(image_paths):
html_content += f'<p><img src="cid:image{i + 1}"></p>'
html_message = MIMEText(html_content, 'html', 'utf-8') # 正文
msg.attach(html_message)
if image_paths:
# 添加多张图片附件
for i, image_path in enumerate(image_paths):
with open(image_path, 'rb') as f:
img = MIMEImage(f.read())
img.add_header('Content-ID', f'<image{i + 1}>')
msg.attach(img)
"""
# 非SSL,如果为SSL则看下面
# server = smtplib.SMTP(MAIL['smtp'])
# 使用SSL连接SMTP服务器
"""
# 使用SSL连接SMTP服务器
server = smtplib.SMTP_SSL(MAIL['smtp'], MAIL['port'])
# 登陆邮箱发送邮件
server.login(MAIL['from'], MAIL['pwd'])
server.sendmail(MAIL['from'], [receiver], msg.as_string())
logging.info('发送邮件成功')
except Exception as e:
logging.error(f"发送邮件失败: {e}")
logging.error(traceback.format_exc())
if __name__ == '__main__':
image_paths = [r"C:\Users\Lenovo\Pictures\ZydnEQlw7nU=FmgT=JPXqamTy6hcRZRVfQdhRl=2nfIGq1530172365562.gif", r"C:\Users\Lenovo\Pictures\微信截图_20240110085422_cleanup.png"]
asyncio.run(email_notification(image_paths=image_paths))