【Python使用 STARTTLS 替代 SMTP_SSL解决发送邮件ssl报错】

📅 2026/8/1 9:59:07 👁️ 阅读次数 📝 编程学习
【Python使用 STARTTLS 替代 SMTP_SSL解决发送邮件ssl报错】

文章目录

    • python发送邮件报错:EOF occurred in violation of protocol
    • ssl正常发送邮件过程
    • 原因分析
    • 解决方案

python发送邮件报错:EOF occurred in violation of protocol

有的电脑可以使用smtplib包的SMTP_SSL方法发送邮件,有些不行(可能公司服务器禁用了服务)


ssl正常发送邮件过程

# 发送try:withsmtplib.SMTP_SSL(EMAIL_CONFIG['smtp_host'],EMAIL_CONFIG['smtp_port'])asserver:server.login(EMAIL_CONFIG['sender'],EMAIL_CONFIG['password'])server.sendmail(EMAIL_CONFIG['sender'],EMAIL_CONFIG['receiver'],msg.as_string())print("✅ 邮件发送成功")exceptExceptionase:print(f"❌ 邮件发送失败:{e}")raise

原因分析

参考网上资料:

该错误通常源于客户端与服务器之间的SSL/TLS协议版本不匹配,特别是在服务器禁用SSLv2而客户端默认尝试使用PROTOCOL_SSLv23时


解决方案

DS提供解决方案:使用 STARTTLS 替代 SMTP_SSL
这是一种更标准、兼容性更好的做法。它先建立明文连接,再通过 starttls() 命令升级为 TLS 加密。

try:# with smtplib.SMTP_SSL(EMAIL_CONFIG['smtp_host'], EMAIL_CONFIG['smtp_port'],context=context) as server:# server.login(EMAIL_CONFIG['sender'], EMAIL_CONFIG['password'])# server.sendmail(EMAIL_CONFIG['sender'], EMAIL_CONFIG['receiver'], msg.as_string())withsmtplib.SMTP(EMAIL_CONFIG['smtp_host'],EMAIL_CONFIG['smtp_port'])asserver:server.starttls()# 显式升级为 TLS 连接server.login(EMAIL_CONFIG['sender'],EMAIL_CONFIG['password'])server.sendmail(EMAIL_CONFIG['sender'],EMAIL_CONFIG['receiver'],msg.as_string())print("✅ 邮件发送成功")exceptExceptionase:print(f"❌ 邮件发送失败:{e}")raise