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

向Yahoo.com域名发送邮件时出现smtplib错误求助

问题描述

问题代码片段

server = 'smtp.mail.yahoo.com' if 'yahoo.com' in mail else 'smtp.gmail.com'
port = 465 if 'yahoo.com' in mail else 587
        
with smtplib.SMTP(server, port) as connection:
    connection.starttls()
    connection.login(MY_EMAIL, PASSWORD)
    connection.sendmail(
        from_addr=MY_EMAIL,
        to_addrs=mail,
        msg=f'Subject: Happy Birthday\n\n{reformatted_template}'

向Gmail域名发送邮件一切正常,但向Yahoo域名发送时抛出如下错误:

smtplib.SMTPConnectError: (-1, b'\x02\x01Z\x15\x03\x03\x00\x02\x01\x00')

尝试过以下修复方法但均无效:

  • 使用smtplib.SMTP_SSL替代smtplib.SMTP
  • 将端口改为465
  • 确认MY_EMAIL和PASSWORD无拼写错误

使用smtplib.SMTP_SSL时,抛出另一个错误:

smtplib.SMTPServerDisconnected: Connection unexpectedly closed

解决方法

针对Yahoo邮箱的SMTP服务,核心问题出在验证方式和配置搭配上,按以下步骤修复:

  1. 生成Yahoo应用专用密码
    Yahoo已不再支持用账号原密码进行SMTP登录,必须生成应用专用密码:
  • 登录Yahoo账号,进入「账户安全」面板
  • 找到「应用专用密码」选项,生成一个仅用于SMTP服务的密码,替换代码中的PASSWORD
  1. 修正SMTP配置搭配
    Yahoo的SMTP加密方式和端口必须严格对应:
  • 使用SMTP_SSL时,端口固定为465,不需要调用starttls()(因为SSL连接本身已加密)
  • 使用SMTP+starttls()时,端口用587

修正后的代码示例:

import smtplib

if 'yahoo.com' in mail:
    server = 'smtp.mail.yahoo.com'
    # SMTP_SSL + 465端口方案(推荐)
    with smtplib.SMTP_SSL(server, 465) as connection:
        connection.login(YOUR_YAHOO_EMAIL, YAHOO_APP_PASSWORD)
        connection.sendmail(
            from_addr=YOUR_YAHOO_EMAIL,
            to_addrs=mail,
            msg=f'Subject: Happy Birthday\r\n\r\n{reformatted_template}'
        )
else:
    # Gmail原有配置保持不变
    server = 'smtp.gmail.com'
    port = 587
    with smtplib.SMTP(server, port) as connection:
        connection.starttls()
        connection.login(YOUR_GMAIL_EMAIL, YOUR_GMAIL_PASSWORD)
        connection.sendmail(
            from_addr=YOUR_GMAIL_EMAIL,
            to_addrs=mail,
            msg=f'Subject: Happy Birthday\r\n\r\n{reformatted_template}'
        )
  1. 规范邮件格式
    部分邮件服务器对换行符要求严格,将\n替换为\r\n确保SMTP协议兼容(如上面代码中msg的格式)

  2. 检查账号安全设置
    确保Yahoo账号未开启「登录验证」限制,若开启需确保应用专用密码已正确生成


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 03:02:39