【问题标题】:Send a email through googleapi gmail python using oauth2使用 oauth2 通过 googleapi gmail python 发送电子邮件
【发布时间】:2012-10-01 09:48:23
【问题描述】:

我正在尝试使用 OAuth 2 以用户身份发送电子邮件。在 Google 的网站上 they state

本文档定义了与 IMAP AUTHENTICATE 和 SMTP AUTH 命令一起使用的 SASL XOAUTH2 机制。此机制允许使用 OAuth 2.0 访问令牌对用户的 Gmail 帐户进行身份验证。

使用他们的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 中重新进行身份验证,它会起作用.. 有什么想法吗?

try:
    smtp_conn.sendmail('fromt@test.com', 'to@test.com', 'cool')
except:
    smtp_conn.docmd('AUTH', 'XOAUTH2 ' + base64.b64encode(auth_string))
    smtp_conn.sendmail('from@test.com', 'to@test.com', 'cool')

【问题讨论】:

  • 您应该使用 to@example.com。 to@test.com 可能是一个真实的电子邮件地址,在这种情况下,您可能会向他们发送垃圾邮件。
  • 这些只是示例电子邮件,用于展示代码的工作原理......当我实际运行代码时,我使用自己的电子邮件

标签: python smtp gmail google-api oauth-2.0


【解决方案1】:

在 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))

【讨论】:

  • 你为什么要这样做两次?如果是这样,那么 try catch 是如何工作的?
猜你喜欢
  • 2015-09-28
  • 2022-08-14
  • 1970-01-01
  • 2016-09-09
  • 2020-10-14
  • 1970-01-01
  • 2012-01-07
  • 2023-03-19
相关资源
最近更新 更多