You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将test_file1捕获的异常传递到test_file2并发送含异常详情的HTML邮件

实现方案

核心逻辑是将test_file2的发邮件逻辑封装为可接收异常参数的函数,test_file1捕获异常后直接调用该函数传递参数,无需额外中间存储。

第一步:修改test_file2.py

将原有发邮件逻辑封装为send_exception_mail函数,接收异常详情和错误行号两个入参,同时修正HTML模板的变量占位符,匹配预期输出格式:

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def send_exception_mail(exp_msg, line_no):
    me = "my@email.com"
    you = "your@email.com"
    msg = MIMEMultipart('alternative')
    msg['Subject'] = "异常告警通知"
    msg['From'] = me
    msg['To'] = you
    
    text = f"Exception mail\nException Details: {exp_msg}\nFound Exception!\nError on line {line_no}"
    # 适配预期的HTML邮件格式
    html = f"""\
    <html>
      <body>
        <p>>> <b>Exception Details:</b> {exp_msg}</p>
        <p>>> Found Exception!</p>
        <p>>> <b>Error on line {line_no}</b></p>
      </body>
    </html>
    """
    
    part1 = MIMEText(text, 'plain')
    part2 = MIMEText(html, 'html')
    
    msg.attach(part1)
    msg.attach(part2)
    mail = smtplib.SMTP('smtp.gmail.com', 587)
    mail.ehlo()
    mail.starttls()
    # 注意:gmail需使用应用密码登录,需提前在账号安全设置中开启
    mail.login('userName', 'password')
    mail.sendmail(me, you, msg.as_string())
    mail.quit()

第二步:修改test_file1.py

导入test_file2的发邮件函数,捕获异常时将异常信息和行号作为参数传入调用:

import sys
# 导入test_file2的发邮件函数
from test_file2 import send_exception_mail

try:
    print(5/0)
except Exception as e:
    exp_msg = str(e)
    error_line = sys.exc_info()[-1].tb_lineno
    # 控制台打印保持原有逻辑
    print(exp_msg)
    print(f'Error on line {error_line}')
    # 调用发邮件接口传递异常信息
    send_exception_mail(exp_msg, error_line)

验证说明

直接运行test_file1.py即可触发异常捕获,自动调用邮件发送逻辑,收到的HTML邮件将完全匹配给定的预期格式。

内容的提问来源于stack exchange,提问作者Ansh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 15:27:05