使用python的电子邮件自动化时出错

时间:2020-10-26 19:24:40

标签: python python-3.x ssl automation smtplib

我已经正确配置了我用于“密码”的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>

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

1 个答案:

答案 0 :(得分:0)

这可能是几年前Google引入的安全性增强问题。如果您的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帐户成功测试了这一点。