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

使用Python smtplib发送Gmail邮件时遇[Errno 60]超时错误求助

问题排查与解决办法

1. 未指定SMTP端口导致连接超时

Gmail的SMTP服务需指定587端口,你的代码仅填写了smtp.gmail.com,未加端口时smtplib默认使用25端口,该端口多数网络会封禁,或Gmail未监听,直接引发连接超时。

修改SMTP初始化代码:

with smtplib.SMTP("smtp.gmail.com", 587) as connection:

2. 发件人邮箱地址存在输入错误

代码中sender_email = "gXXXXXXXXX^0@gmail.com"包含非法符号^,与你定义的正确邮箱地址email不一致,即使连接成功,发送环节也会出错。建议直接复用正确变量:

sender_email = email  # 避免手动输入错误

3. 网络与权限限制

  • 检查Mac防火墙设置:打开「系统设置」→「网络」→「防火墙」,确认Python/VS Code的网络连接权限未被限制。
  • 若处于公司/学校网络,SMTP 587端口可能被防火墙封禁,可切换至个人热点测试。
  • 确认Google账号已开启两步验证,且使用的是正确的应用专用密码(App Password),普通密码无法用于SMTP登录。

4. 补充邮件格式必要字段

部分SMTP服务器要求明确指定发件人、收件人字段,避免被拒收或报错,建议补充到邮件内容中:

message = f"""\
From: {sender_email}
To: {receiver_email}
Subject: Hello from Python

This is a test email sent from Python.
"""

完整修正代码示例

import smtplib

email = "gXXXXXXXXX0@gmail.com"
password_email = "XXXX XXXX XXXX XXXX"  # Google应用专用密码

if not email or not password_email:
    print("请设置邮箱和密码环境变量。")
    exit()

sender_email = email
receiver_email = "gXXXXXXXXXX03@gmail.com"
message = f"""\
From: {sender_email}
To: {receiver_email}
Subject: Hello from Python

This is a test email sent from Python.
"""

try:
    with smtplib.SMTP("smtp.gmail.com", 587) as connection:
        connection.starttls()
        connection.login(user=email, password=password_email)
        connection.sendmail(from_addr=sender_email, to_addrs=receiver_email, msg=message)
    print("邮件发送成功。")
except Exception as e:
    print(f"发生错误: {e}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 15:43:21