Files
fcb_photo_review/auto_email/error_email.py

74 lines
3.7 KiB
Python

import datetime
import logging
import smtplib
from email.mime.text import MIMEText
from auto_email import ERROR_EMAIL_CONFIG
def send_error_email(program_name, error_name, error_detail):
"""
程序出错时发送邮件提醒
:param program_name: 运行的程序名
:param error_name: 错误名
:param error_detail: 错误的详细信息
:return:
"""
# SMTP 服务器配置
smtp_server = ERROR_EMAIL_CONFIG["smtp_server"]
port = ERROR_EMAIL_CONFIG["port"]
sender = ERROR_EMAIL_CONFIG["sender"]
authorization_code = ERROR_EMAIL_CONFIG["authorization_code"]
receivers = ERROR_EMAIL_CONFIG["receivers"]
retry_times = ERROR_EMAIL_CONFIG["retry_times"]
# 获取程序出错的时间
error_time = datetime.datetime.strftime(datetime.datetime.today(), "%Y-%m-%d %H:%M:%S:%f")
# 邮件内容
subject = f"【程序异常提醒】{program_name} {error_time}" # 邮件的标题
content = f'''<div class="emailcontent" style="width:100%;max-width:720px;text-align:left;margin:0 auto;padding-top:80px;padding-bottom:20px">
<div class="emailtitle">
<h1 style="color:#fff;background:#51a0e3;line-height:70px;font-size:24px;font-weight:400;padding-left:40px;margin:0">程序运行异常通知</h1>
<div class="emailtext" style="background:#fff;padding:20px 32px 20px">
<p style="color:#6e6e6e;font-size:13px;line-height:24px">程序:<span style="color:red;">【{program_name}】</span>运行过程中出现异常错误,下面是具体的异常信息,请及时核查处理!</p>
<table cellpadding="0" cellspacing="0" border="0" style="width:100%;border-top:1px solid #eee;border-left:1px solid #eee;color:#6e6e6e;font-size:16px;font-weight:normal">
<thead>
<tr>
<th colspan="2" style="padding:10px 0;border-right:1px solid #eee;border-bottom:1px solid #eee;text-align:center;background:#f8f8f8">程序异常详细信息</th>
</tr>
</thead>
<tbody>
<tr>
<td style="padding:10px 0;border-right:1px solid #eee;border-bottom:1px solid #eee;text-align:center;width:100px">异常简述</td>
<td style="padding:10px 20px 10px 30px;border-right:1px solid #eee;border-bottom:1px solid #eee;line-height:30px">{error_name}</td>
</tr>
<tr>
<td style="padding:10px 0;border-right:1px solid #eee;border-bottom:1px solid #eee;text-align:center">异常详情</td>
<td style="padding:10px 20px 10px 30px;border-right:1px solid #eee;border-bottom:1px solid #eee;line-height:30px">{error_detail}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
''' # 邮件的正文部分
# 实例化一个文本对象
massage = MIMEText(content, 'html', 'utf-8')
massage['Subject'] = subject # 标题
massage['From'] = sender # 发件人
receivers_str = ','.join(receivers)
massage['To'] = receivers_str # 收件人
for i in range(retry_times):
try:
mail = smtplib.SMTP_SSL(smtp_server, port) # 连接SMTP服务
mail.login(sender, authorization_code) # 登录到SMTP服务
mail.sendmail(sender, receivers, massage.as_string()) # 发送邮件
mail.quit()
logging.info("成功发送了一封邮件到" + receivers_str)
break
except smtplib.SMTPException:
if i == retry_times - 1:
logging.warning("邮件发送失败!")