如何使用 2 因素身份验证从 python 发送电子邮件?

tha*_*der 4 python email gmail smtp google-2fa

我创建了 python 文件,可以使用打开的不太安全的应用程序发送电子邮件,但我需要将其关闭。如何使用 2FA 发送电子邮件?

# import simple mail transfer protocol library
import smtplib 

# import EmailMessage method
from email.message import EmailMessage

contacts = ['<email@email.com>', '<email2@email.com>']
EMAIL_ADDRESS = '<my_gmail>'
EMAIL_PASSWORD = '<my_gmail_password>'

# Create empty Email Message object
msg = EmailMessage()
msg['Subject'] = 'Automated python email sender 5'
msg['From'] = EMAIL_ADDRESS
msg['To'] = contacts
msg.set_content('<sample_content>')

# contact manager we will make sure our connection is closed automatically without us doing it manually
# 465 is the port number for plain SMTP_SSL
# SMTP_SSL means you do not have to use ehlo() ans starttls()
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:

  smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
  smtp.send_message(msg)

Run Code Online (Sandbox Code Playgroud)

我应该添加什么才能使 2FA 发挥作用?

DaI*_*mTo 5

我认为您需要设置一个应用程序密码,以便您可以从不支持两步验证的设备上的应用程序登录您的 Google 帐户。了解更多

它基本上是在用户谷歌帐户中设置的。

另一件需要注意的事情是显示验证码

如果这不起作用,您可能需要研究Xoauth2

如果您需要 2fa

如果您想支持 2fa,那么您不应该使用 SMTP 服务器,而应该通过 Gmail API 并使用 Oauth2,这将提示用户通过其 google 帐户进行连接,并且 google 将自行控制 2fa。SMTP 服务器并非设计用于处理 2fa