import datetime import logging import smtplib from email.mime.text import MIMEText from tenacity import retry, stop_after_attempt, wait_random from auto_email import ERROR_EMAIL_CONFIG, TRY_TIMES, MIN_WAIT_TIME, MAX_WAIT_TIME from log import HOSTNAME @retry(stop=stop_after_attempt(TRY_TIMES), wait=wait_random(MIN_WAIT_TIME, MAX_WAIT_TIME), reraise=True, after=lambda x: logging.warning("发送邮件失败!")) def send_email(email_config, massage): smtp_server = email_config["smtp_server"] port = email_config["port"] sender = email_config["sender"] authorization_code = email_config["authorization_code"] receivers = email_config["receivers"] 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(f"成功发送了一封邮件到[{','.join(receivers)}]") def send_error_email(program_name, error_name, error_detail): """ 程序出错时发送邮件提醒 :param program_name: 运行的程序名 :param error_name: 错误名 :param error_detail: 错误的详细信息 :return: """ # SMTP 服务器配置 sender = ERROR_EMAIL_CONFIG["sender"] receivers = ERROR_EMAIL_CONFIG["receivers"] # 获取程序出错的时间 error_time = datetime.datetime.strftime(datetime.datetime.today(), "%Y-%m-%d %H:%M:%S:%f") # 邮件内容 subject = f"【程序异常提醒】{program_name}({HOSTNAME}) {error_time}" # 邮件的标题 content = f'''
程序:【{program_name}】运行过程中出现异常错误,下面是具体的异常信息,请及时核查处理!
| 程序异常详细信息 | |
|---|---|
| 异常简述 | {error_name} |
| 异常详情 | {error_detail} |