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

使用Python发邮件遇smtplib.SMTPConnectError(421)错误求助

解决smtplib.SMTPConnectError: (421, b'Service not available')问题

针对你的Gmail SMTP发送问题,按以下步骤排查:

1. 检查Gmail账号安全设置

  • 若账号开启了两步验证,必须使用**应用专用密码(App Password)**替代普通密码登录,普通密码会被服务器直接拒绝。
  • 未开启两步验证的账号,需在Google账号设置中开启"不太安全的应用访问"(注:该选项已逐步被Google淘汰,优先推荐使用应用专用密码)。

2. 修正邮件格式

sendmail的msg参数必须符合邮件协议规范,不能仅传递纯文本内容。正确格式需包含邮件头信息,示例:

msg = """From: {sender}
To: {receiver}
Subject: 测试邮件

hello
""".format(sender=my_email, receiver="okoyek10@yahoomail.com")

缺少标准头信息可能导致服务器判定请求无效,触发错误。

3. 排查网络连接问题

  • 确认本地防火墙、杀毒软件未拦截587端口的出站连接。
  • 若使用代理或VPN,尝试关闭后再测试,部分代理会干扰SMTP连接的正常建立。
  • 可通过telnet smtp.gmail.com 587命令测试端口连通性,若无法连接,说明网络层面存在阻碍。

4. 优化代码结构(可选)

使用上下文管理器with可自动管理连接生命周期,避免手动关闭可能引发的异常:

import smtplib

my_email = "okoyekennethoptimizer@gmail.com"
password = "你的应用专用密码"

msg = """From: {sender}
To: {receiver}
Subject: 测试邮件

hello
""".format(sender=my_email, receiver="okoyek10@yahoomail.com")

with smtplib.SMTP("smtp.gmail.com", 587) as connection:
    connection.starttls()
    connection.login(user=my_email, password=password)
    connection.sendmail(from_addr=my_email, to_addrs="okoyek10@yahoomail.com", msg=msg)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 22:19:22