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

如何使用Python登录Gmail?代码第17行报错求助

Gmail邮件发送代码报错修复方案

核心问题分析(第17行报错原因)

  • SMTP端口与协议不匹配:smtplib.SMTP_SSL是SSL加密连接,对应Gmail的端口是465;你写的587是普通SMTP连接后开启STARTTLS加密的端口,混用会直接触发报错。
  • 目标邮箱格式无效:to_email = 'dasdladalffhalf'不是合法邮箱地址,必须包含@和域名后缀(比如xxx@gmail.com)。
  • Gmail登录权限限制:直接用账号密码登录大概率失败,需开启两步验证后生成应用专用密码,或临时允许“不够安全的应用访问”(不推荐后者)。

修正后的代码

main.py

import config as cfg
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

msg = MIMEMultipart()
# 修正:填写合法的目标邮箱地址
to_email = 'target_email@example.com'

msg['Subject'] = input('Topic: ')
msg['From'] = cfg.LOGIN
# 补充收件人字段,符合邮件规范
msg['To'] = to_email

msg_body = input('Text: ')
msg.attach(MIMEText(msg_body, 'plain'))

# 方案1:SMTP_SSL+465端口(推荐)
server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
# 方案2:普通SMTP+STARTTLS(587端口)
# server = smtplib.SMTP('smtp.gmail.com', 587)
# server.starttls()

server.login(cfg.LOGIN, cfg.PASSWORD)
server.sendmail(cfg.LOGIN, to_email, msg.as_string())
server.quit()  # 关闭连接,释放资源

config.py

# 替换为你的Gmail邮箱
LOGIN = 'your_gmail_account@gmail.com'
# 替换为两步验证后生成的应用专用密码
PASSWORD = 'your_app_specific_password'

额外注意事项

  • 应用专用密码需在Google账号设置中开启两步验证后,在“安全”选项里生成。
  • 务必确认目标邮箱地址拼写正确,否则邮件会被退回或无法发送。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 11:15:36