【发布时间】:2020-09-12 07:19:00
【问题描述】:
我想通过 Python 使用 Gmail OAuth 协议发送电子邮件。对于某些背景,我的程序的一般过程需要用户输入,创建图像,然后发送电子邮件。从理论上讲,该程序可能会在某个时候发送数百封电子邮件。我遇到的问题是,当我尝试为 OAuth 检索令牌时,我收到了未经授权的重定向 url 错误。该应用程序尚未经过验证,我也没有 G Suite 管理员帐户,但我浏览的每个教程都没有提及这一点。我启用的唯一重定向 URL 是 https://developers.google.com/oauthplayground 和 http://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)
【问题讨论】:
-
因此,您需要在 OAuth 同意屏幕中添加
redirect_uri,然后添加 redownload the JSON file with the credentials。尝试这样做并确认您是否仍然遇到此错误的问题。 -
OAuth 同意屏幕在哪里?因为您列出的说明就是我的问题所述。
-
好的,但现在我收到关于重定向 url 如何的授权错误:localhost:8080 不存在。然而我提供了localhost:8000/oauth2callback 和127.0.0.1:8887/oauth2callback 作为重定向。
-
您需要实际使用
run_local_server才能使该页面存在。这将处理文档中所述的所有令牌交互。
标签: python oauth-2.0 google-oauth gmail-api