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

Python SMTP配置正确可登录但无法发送邮件问题求助

SMTP发送OTP时连接意外关闭的问题解决

问题场景

通过Zoho SMTP发送OTP(同步保存到数据库),前两次发送成功后彻底失效:配置能正常登录,但执行sendmail时卡住,最终抛出smtplib.SMTPServerDisconnected: Connection unexpectedly closed错误。

相关代码

message = """Subject: Your OTP
    Hi, your your otp is {otp}"""
from_address = "REDACTED"
password = "REDACTED"
context = ssl.create_default_context()
print('xyz')
msg = message.format(otp=otp)
with smtplib.SMTP_SSL(host="smtppro.zoho.eu", port = 465, context=context) as server:
    print('xyz')
    server.login(from_address, password)
    print('logs')
    server.ehlo('127.0.0.1') ## 试过加ehlo和不加
    print(email) ## 打印完这个就卡住
    server.sendmail(
        from_address,
        email,
        msg
    )
    print('sent')
    server.quit() ## 前两次忘记加这个
    print('quit')
return "OTP sent to your email"

报错信息

File "/home/blank/.local/lib/python3.11/site-packages/flask/app.py", line 1469, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/blank/scripts/test/emails.py", line 56, in sendmail
    server.sendmail(
  File "/usr/lib/python3.11/smtplib.py", line 902, in sendmail
    (code, resp) = self.data(msg)
                   ^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/smtplib.py", line 580, in data
    (code, msg) = self.getreply()
                  ^^^^^^^^^^^^^^^
  File "/usr/lib/python3.11/smtplib.py", line 405, in getreply
    raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed

已尝试操作:补上server.quit()、重启服务器两次、切换账户密码/应用专用密码(均能正常登录)


排查与解决方法

  1. 修复邮件格式错误
    SMTP协议要求邮件头(如Subject)和正文之间必须空一行,当前代码里没有这个分隔,会导致服务器无法解析邮件,直接断开连接。同时去掉正文多余缩进:
    message = """Subject: Your OTP
    
    

Hi, your OTP is {otp}"""

2. **移除手动`server.quit()`**
用`with`上下文管理器创建SMTP连接时,会自动调用关闭逻辑,手动调用`server.quit()`会触发重复关闭,引发异常,直接删掉这行代码。

3. **调整EHLO调用方式**
不要指定`127.0.0.1`作为EHLO参数,直接调用`server.ehlo()`(不带参数),让服务器自动识别你的服务器标识,避免被判定为可疑请求。

4. **添加连接超时**
给SMTP连接设置超时时间,避免无限等待,同时快速定位连接类问题:
```python
with smtplib.SMTP_SSL(host="smtppro.zoho.eu", port=465, context=context, timeout=30) as server:
  1. 检查Zoho发送限制
    Zoho对免费/基础账户有发送频率限制,短时间多次发送可能触发临时封禁。登录Zoho邮件后台查看是否有发送限制警告,降低测试频率或申请提升额度。

  2. 开启调试模式
    开启SMTP调试模式,查看和服务器的交互细节,精准定位问题:

    server.set_debuglevel(1)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 15:35:10