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

Python smtplib异常捕获问题:SMTPResponseException无法捕获553错误

解决Python smtplib错误码捕获问题

问题分析

你遇到的核心问题是:无效收件人触发的SMTPRecipientsRefused异常并未被SMTPResponseException分支捕获。这是因为在Python的smtplib模块中,SMTPResponseException并非所有带SMTP错误码异常的基类——SMTPRecipientsRefused、SMTPHeloError等特定场景异常是直接继承自SMTPException的独立类,和SMTPResponseException属于同级分支。

修正后的代码

要正确捕获各类SMTP错误并提取错误码执行后续逻辑,需单独捕获特定异常,同时保留通用异常处理作为兜底:

def send_email():
    try:
        with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as smtp:
            smtp.login(email_sender, email_password)
            smtp.sendmail(email_sender, email_receiver, send_message.as_string())
            print("Email successfully sent!")
    except smtplib.SMTPRecipientsRefused as error:
        # 处理收件人相关错误,error.recipients是字典,键为收件人,值为(错误码, 错误信息)
        for recipient, (code, msg) in error.recipients.items():
            print(f"收件人 {recipient} 发送失败:")
            print(f"错误码: {code}")
            print(f"错误信息: {msg.decode('utf-8')}")
            # 这里可以添加对应错误码的后续逻辑,比如553时标记无效地址
    except smtplib.SMTPResponseException as error:
        error_code = error.smtp_code
        error_message = error.smtp_error.decode('utf-8')
        print(f"错误码: {error_code}")
        print(f"错误信息: {error_message}")
    except smtplib.SMTPException as error:
        # 兜底捕获所有SMTP相关异常
        print(f"SMTP错误发生: {str(error)}")

关键说明

  1. 异常捕获顺序:必须把具体异常(如SMTPRecipientsRefused)放在通用异常前面,否则会被上层分支拦截。
  2. SMTPRecipientsRefused结构:该异常的recipients属性是字典,存储了每个失败收件人的错误信息,字节型的错误消息需用decode('utf-8')转为字符串。
  3. 错误码扩展:现在可以针对不同错误码(如553)编写定制逻辑,比如记录无效地址、触发重试流程等。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 12:50:25