【问题标题】:Python: Get Gmail server with smtplib never endsPython:使用 smtplib 获取 Gmail 服务器永无止境
【发布时间】:2026-01-01 06:25:01
【问题描述】:

我只是尝试过:

>>> import smtplib
>>> server = smtplib.SMTP('smtp.gmail.com:587')

在我的 Python 解释器中,但第二条语句永远不会结束。

有人可以帮忙吗?

【问题讨论】:

  • 你解决过这个问题吗?

标签: python smtplib


【解决方案1】:

您可能会发现您需要登录名和密码作为成功登录的先决条件。
试试这样的:

import smtplib
ServerConnect = False
try:
    smtp_server = smtplib.SMTP('smtp.gmail.com','587')
    smtp_server.login('your_login', 'password')
    ServerConnect = True
except SMTPHeloError as e:
    print "Server did not reply"
except SMTPAuthenticationError as e:
    print "Incorrect username/password combination"
except SMTPException as e:
    print "Authentication failed"

如果您收到“连接意外关闭”,请尝试将服务器行更改为:

smtp_server = smtplib.SMTP_SSL('smtp.gmail.com','465')

请注意:Google 可能会阻止来自不使用现代安全标准的某些应用或设备的登录尝试。由于这些应用程序和设备更容易被入侵,因此阻止它们有助于确保您的帐户安全。见:https://support.google.com/accounts/answer/6010255?hl=en

Gmail 设置:

SMTP Server (Outgoing Messages)     smtp.gmail.com  SSL     465     
    smtp.gmail.com  StartTLS    587
IMAP Server (Incoming Messages)     imap.gmail.com  SSL     993    
    Please make sure, that IMAP access is enabled in the account settings.
Login to your account and enable IMAP.
You also need to enable "less secure apps" (third party apps) in the Gmail settings:
https://support.google.com/accounts/answer/6010255?hl=en
See also: How to enable IMAP/POP3/SMTP for Gmail account

如果所有其他方法都无法从命令行尝试ping gmail.com

【讨论】:

  • 实际上,smtp_server.login('your_login', 'password') 永远无法到达。解释器一直停留在上一行。
  • 然后将其粘贴在try...except.. 语句中并打印出错误。
  • 我没有收到任何错误,这是我的问题。解释器只是卡住了,什么也没有打印出来。 SMTP_SSL 也不起作用。我收到了SSL: UNKNOWN_PROTOCOL
  • 查看我的新编辑并在 python 解释器 import smtplib 后跟 help (smtplib.SMTP_SSL) 如果失败,您的 smtplib 库有问题。如果成功,请继续输入上面的代码,直到得到结果。