首页 > 解决方案 > Gmail Api 重定向 URL 问题并在 Python 中使用 OAuth

问题描述

我想使用来自 Python 的 Gmail OAuth 协议发送电子邮件。对于某些背景,我的程序的一般过程需要用户输入,创建图像,然后发送电子邮件。从理论上讲,该程序可能会在某个时候发送数百封电子邮件。我遇到的问题是,当我尝试为 OAuth 检索令牌时,我收到了未经授权的重定向 url 错误。该应用程序尚未经过验证,我也没有 G Suite 管理员帐户,但我浏览的每个教程都没有提及这一点。我启用的唯一重定向网址是https://developers.google.com/oauthplaygroundhttp://localhost:8080/oauth2callback,它们都在我从谷歌开发人员的凭据页面下载的 client_secret.json 文件中。

这是我所拥有的:

import base64
import httplib2
from email.mime.text import MIMEText
from apiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import run

# Path to the client_secret.json file downloaded from the Developer Console
CLIENT_SECRET_FILE = 'client_secret.json'

# Check https://developers.google.com/gmail/api/auth/scopes for all available scopes
OAUTH_SCOPE = 'https://www.googleapis.com/auth/gmail.compose'

# Location of the credentials storage file
STORAGE = Storage('gmail.storage')

# Start the OAuth flow to retrieve credentials
flow = flow_from_clientsecrets(CLIENT_SECRET_FILE, scope=OAUTH_SCOPE)
http = httplib2.Http()

# Try to retrieve credentials from storage or run the flow to generate them
# This is where it fails.
credentials = STORAGE.get()
if credentials is None or credentials.invalid:
  credentials = run(flow, STORAGE, http=http)

# Authorize the httplib2.Http object with our credentials
http = credentials.authorize(http)

# Build the Gmail service from discovery
gmail_service = build('gmail', 'v1', http=http)

# create a message to send
message = MIMEText("Message goes here.")
message['to'] = "my_email@gmail.com"
message['from'] = "my_email@gmail.com"
message['subject'] = "your subject goes here"
body = {'raw': base64.b64encode(message.as_string())}

# send it
try:
  message = (gmail_service.users().messages().send(userId="me", body=body).execute())
  print('Message Id: %s' % message['id'])
  print(message)
except Exception as error:
  print('An error occurred: %s' % error)

标签: pythonoauth-2.0google-oauthgmail-api

解决方案


这已在评论中进行了更详细的讨论。

基本上,当您创建一个与谷歌服务交互的应用程序时,用户需要接受您的应用程序将具有的范围。这意味着您需要创建一个Oauth Consent Screen

因此,您在Google Console Cloud中转到您的项目,在那里选择Api & Services > OAuth 同意屏幕或转到此链接。要创建该 OAuth 同意屏幕,系统将提示您两个选项:

  • 内部:仅适用于 G Suite 帐户,您的应用只能由您组织的成员访问
  • 外部:非 G Suite 帐户的唯一选项,如果您访问“强大”范围,则需要验证应用程序,否则将被标记为未验证。

对于您的情况(这似乎是个人使用/开发),请继续处理未经验证的应用程序选择External

OAuth 同意屏幕创建

您可以看到实际上 google 指出我需要验证,但在创建时我收到一个屏幕提示,说明我的应用程序是未经验证的应用程序

OAuth 屏幕

仅用于个人用途(它有 100 个用户上限)。


推荐阅读