我正试图开发一个功能,从一个Gmail帐户发送电子邮件与自己的域。例如:person1@companyname.com
要求是我不能在谷歌帐户中启用2因素身份验证,也不允许不太安全的应用程序。
那么,什么是最好的方法呢?我在Youtube上看过一个教程,但是他们使用credential.json或client.json文件进行身份验证,而没有解释获取这些文件或其内容的正确方法。
这是我到目前为止的代码:
# Sending email
try:
password = 'appPasswordIsSupposedtoBePlacedHereButIAmNotAllowedToUseit'
sender_email = 'person1@companyname.com'
recipient_email = ['person2@companyname.com', 'testemail@gmail.com']
subject = 'blablba'
body = 'blabla'
em= EmailMessage()
em['From']= sender_email
em['To'] = ", ".join(recipient_email)
em['subject'] = subject
em.set_content(body)
context = ssl.create_default_context()
with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as smtp:
smtp.login(sender_email, password)
smtp.sendmail(sender_email, recipient_email, em.as_string())
except Exception as e:
errors = errores + ' Error while sending the email: ' + str(e)
logging.warning(errors)
1条答案
按热度按时间bf1o4zei1#
你其实有两个选择。
1.为你的域创建一个google workspace帐户,然后你可以使用服务帐户和域宽deligation来用gmail API做这件事。
1.使用Xoauth2授权用户并存储刷新令牌。
2023: How I access GMail SMTP without enabling 2fa. (Python oauth2)
样本Xoauth2
访问令牌和刷新令牌将存储在'token.json'中。只需在谷歌开发者控制台上创建安装的应用程序凭据,并将应用程序设置为生产,如果它的单个用户,你不需要验证它。