使用oauth2通过googleapi gmailpython发送电子邮件

2024-06-11 03:49:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用oauth2作为用户发送电子邮件。在谷歌的网站they state

This document defines the SASL XOAUTH2 mechanism for use with the IMAP AUTHENTICATE and SMTP AUTH commands. This mechanism allows the use of OAuth 2.0 Access Tokens to authenticate to a user's Gmail account.

使用他们的oauth2.py中提供的测试

smtp_conn = smtplib.SMTP('smtp.gmail.com', 587)
smtp_conn.set_debuglevel(True)
smtp_conn.ehlo('test')
smtp_conn.starttls()
smtp_conn.docmd('AUTH', 'XOAUTH2 ' + base64.b64encode(auth_string))

在这里,您可以测试是否可以使用提供的访问令牌连接到他们的smtp服务器,但当我尝试使用sendmail发送电子邮件时,我得到了一个失败。在

如果我添加smtp_conn.sendmail('from@test.com', 'to@test.com', 'msg'),则说明我需要进行身份验证。在

从文档中,当我用所需的身份验证字符串发送AUTH命令时,我是否没有进行身份验证?在

谢谢。在

更新*

所以很显然,如果我在try-catch语句的catch中重新进行身份验证,它会起作用。。有什么想法吗?在

^{pr2}$

Tags: thetotestcomauth身份验证usethis
1条回答
网友
1楼 · 发布于 2024-06-11 03:49:27

starttls之后你需要另一个ehlo电话。所以:

    smtp_conn = smtplib.SMTP('smtp.gmail.com', 587)
    smtp_conn.set_debuglevel(True)
    smtp_conn.ehlo()
    smtp_conn.starttls()
    smtp_conn.ehlo()
    smtp_conn.docmd('AUTH', 'XOAUTH2 ' + base64.b64encode(auth_string))

相关问题 更多 >