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

时间:2020-09-09 02:23:21

标签: python email smtp gmail 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)

我应该添加些什么以使2FA正常工作?

1 个答案:

答案 0 :(得分:1)

我相信您需要设置一个应用密码,以便您从不支持两步验证的设备上的应用登录到您的Google帐户。 Learn more

基本上,这就是在用户Google帐户中设置的内容。

要看的另一件事是Display captcha

如果这不起作用,则可能需要调查Xoauth2

如果您需要2fa

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