首页 > 解决方案 > 使用 python 的电子邮件自动化时出错

问题描述

我已正确配置了用于“密码”的 Gmail 应用密码。我启用了两步。我正在使用 python 3.8

import smtplib
import ssl

email = "send@gmail.com" #changed
password = "aeaeaeaeaeaea" #changed
to = "rece@gmail.com"
msg = "Hello, Python here."

server = smtplib.SMTP_SSL("smtp.gmail.com", 465, ssl.create_default_context())

server.login(email, password)

server.sendmail(email , to , msg)

server.quit()

我面临的错误是


C:\Users\Owner\Desktop\cd>python auto_email.py
Traceback (most recent call last):
  File "auto_email.py", line 11, in <module>
    server.login(email, password)
  File "C:\Users\Owner\AppData\Local\Programs\Python\Python38\lib\smtplib.py", line 698, in login
    self.ehlo_or_helo_if_needed()
  File "C:\Users\Owner\AppData\Local\Programs\Python\Python38\lib\smtplib.py", line 605, in ehlo_or_helo_if_needed
    (code, resp) = self.helo()
  File "C:\Users\Owner\AppData\Local\Programs\Python\Python38\lib\smtplib.py", line 434, in helo
    (code, msg) = self.getreply()
  File "C:\Users\Owner\AppData\Local\Programs\Python\Python38\lib\smtplib.py", line 398, in getreply
    raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed

C:\Users\Owner\Desktop\cd>

如何克服这个问题?我的互联网连接速度也不错。

标签: pythonpython-3.xsslautomationsmtplib

解决方案


这可能是谷歌几年前推出的安全增强功能的问题。如果您的 GMail 帐户启用了双因素身份验证(通常是个好主意),请尝试创建一个应用专用密码并在您的代码中使用该密码。在没有双重身份验证的情况下,您可以尝试的另一种方法是允许“不太安全的应用程序”。您可以在此处的 Google 文档中找到详细信息:https: //support.google.com/accounts/answer/6010255?hl=en

更新:尝试以下操作:

import smtplib
import ssl

email = "xxx@gmail.com" #changed
password = "rjyofpcoxcdtycip" #changed
to = "yyy@gmail.com"
msg = "Hello, Python here."

server = smtplib.SMTP("smtp.gmail.com", 587)

server.starttls()

server.login(email, password)

server.sendmail(email , to , msg)

server.quit()

它使用 STARTTLS 进行显式 TLS 连接。我使用带有应用程序密码的 GMail 帐户成功测试了这一点。


推荐阅读