python - 使用 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>
如何克服这个问题?我的互联网连接速度也不错。
解决方案
这可能是谷歌几年前推出的安全增强功能的问题。如果您的 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 帐户成功测试了这一点。
推荐阅读
- javascript - 我不知道这个功能是如何工作的。谁能给我解释一下?
- php - PHP 从 bash 传递参数。如何从 [2] 开始使用 foreach?
- java - Git 和 Java 包名问题
- azure - 在 Azure 中,Ambari Web UI 是否提供信息来建议如何扩展
- swift - 在 Swift (5) 中,如何将“Any...”参数传递给 print() 语句而不将其打印为数组?
- ios - 如何在 iOS 警报中为取消显示不同的颜色?
- c++ - 在 std::ofstream (c++) 中复制 std::cout
- javascript - 如何处理导致不需要的组件重新安装的反应 History.Push()?
- django - Django 表单和引导选择
- javascript - MutationObserver 可以监听不断变化的 DOM 元素顺序吗?