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

发布时间:2026/8/1 9:36:01
【Python使用 STARTTLS 替代 SMTP_SSL解决发送邮件ssl报错】 文章目录python发送邮件报错EOF occurred in violation of protocolssl正常发送邮件过程原因分析解决方案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],contextcontext) 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