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

Python使用smtplib本地发送邮件报SMTPException未定义错误

问题修复指南

报错翻译

你收到的报错NameError: name 'SMTPException' is not defined中文含义为:名称错误:名称“SMTPException”未被定义

核心原因&修复步骤

  • 异常类命名空间错误
    SMTPException是smtplib模块内置的异常类,你没有指定所属模块就直接调用,才触发了未定义报错。修复有两种可选方案:

    1. 导入模块时额外导入该异常类,在开头import smtplib下方加一行:
    from smtplib import SMTPException
    
    1. 捕获异常时补全模块前缀,把except SMTPException:改为:
    except smtplib.SMTPException:
    
  • 遗漏变量定义
    你代码中调用smtpObj.sendmail(sender, receivers, message)时,sender、receivers两个变量没有提前赋值,需要在try代码块前补充定义:

sender = "from@fromdomain.com" # 替换为实际发件人地址
receivers = ["to@todomain.com"] # 接收人地址为列表格式,支持填写多个
  • 本地SMTP服务适配(无需本地存储凭据的实现)
    你当前使用smtplib.SMTP('localhost')调用本地SMTP服务,绝大多数个人设备没有默认开启该服务,你可以使用公共邮箱服务商的SMTP接口,运行时动态输入授权码,不需要将凭据存在本地,完整可运行的Python3示例代码如下:
#!/usr/bin/python3
import smtplib
from getpass import getpass

# 邮件内容配置
sender = "你的发件邮箱地址"
receivers = ["收件人邮箱地址"]
message = """From: From Person <{}>
To: To Person <{}>
MIME-Version: 1.0
Content-type: text/html
Subject: SMTP HTML e-mail test

This is an e-mail message to be sent in HTML format

<b>This is HTML message.</b>
<h1>This is headline.</h1>
""".format(sender, receivers[0])

try:
    # 以QQ邮箱为例,不同服务商SMTP地址和端口不同
    smtpObj = smtplib.SMTP_SSL('smtp.qq.com', 465)
    # 运行时动态输入授权码,不会本地存储
    auth_code = getpass("请输入邮箱SMTP授权码:")
    smtpObj.login(sender, auth_code)
    smtpObj.sendmail(sender, receivers, message)         
    print("Successfully sent email")
except smtplib.SMTPException as e:
    print(f"Error: unable to send email,错误详情:{e}")

注:使用公共邮箱SMTP服务前,需要先在邮箱设置页面开启SMTP功能,获取专属授权码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 00:57:04