使用python时出错';s电子邮件自动化

使用python时出错';s电子邮件自动化,python,python-3.x,ssl,automation,smtplib,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

我已经为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>


C:\Users\Owner\Desktop\cd>python auto\u email.py
回溯(最近一次呼叫最后一次):
文件“auto_email.py”,第11行,在
服务器登录(电子邮件、密码)
文件“C:\Users\Owner\AppData\Local\Programs\Python38\lib\smtplib.py”,第698行,登录
self.ehlo_或helo_如果需要()
文件“C:\Users\Owner\AppData\Local\Programs\Python\Python38\lib\smtplib.py”,第605行,如果需要,在ehlo\u或helo\u中
(代码,resp)=self.helo()
文件“C:\Users\Owner\AppData\Local\Programs\Python\Python38\lib\smtplib.py”,第434行,在helo中
(代码,msg)=self.getreply()
文件“C:\Users\Owner\AppData\Local\Programs\Python\Python38\lib\smtplib.py”,第398行,在getreply中
升起SMTPServerDisconnected(“连接意外关闭”)
smtplib.SMTPServerDisconnected:连接意外关闭
C:\Users\Owner\Desktop\cd>

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

这可能是谷歌几年前推出的安全增强功能的问题。如果您的GMail帐户启用了双因素身份验证(通常是个好主意),请尝试创建特定于应用程序的密码,并在代码中使用该密码。如果没有双因素身份验证,您可以尝试另一种方法,即允许“不太安全的应用程序”。您可以在以下谷歌文档中找到详细信息:

更新:请尝试以下操作:

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帐户成功地测试了这一点。

Update:-我甚至尝试关闭两个因素,并使用安全性较低的应用程序。同样的错误发生谢谢你的测试。我刚刚用您的原始代码的工作版本更新了答案。