【发布时间】:2020-04-30 16:31:30
【问题描述】:
我正在尝试从 python 谷歌云函数调用 User: watch。
我正在笔记本电脑上测试脚本。
我所做的设置:
- 在项目上启用 gmail API
- 使用 json 凭据文件创建服务帐户
- 将服务帐户的客户端 ID 放入Manage API client access,API 范围如下
['https://mail.google.com/','https://www.googleapis.com/auth/admin.directory.user'] - 已验证 G Suite 域范围委派已启用
我不断收到的错误是:
err=('unauthorized_client: Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested.', '{\n "error": "unauthorized_client",\n "error_description": "Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested."\n}')
我已尝试传递服务凭据帐户并设置 userId = TARGET_INBOX,但返回的请求不正确。我已尝试查看与此错误相关的其他 SO 帖子,但没有发现任何我做错的事情。
点文件:
[[source]]
name = "pypi"
url = "https://pypi.org/simple"
verify_ssl = true
[dev-packages]
pytest = "*"
[packages]
flask = "*"
google-cloud-pubsub = "*"
google-api-python-client = "*"
google-auth = "*"
[requires]
python_version = "3.7"
watch_inboxes.py
import os
import google.auth
from google.auth import impersonated_credentials
from google.auth.exceptions import RefreshError
from googleapiclient.discovery import build
import json
from googleapiclient.errors import HttpError
SCOPES = ['https://mail.google.com/', 'https://www.googleapis.com/auth/admin.directory.user']
TARGET_INBOX = '***TARGET_EMAIL_ADDRESS****'
def watch_inboxes(request):
if not os.environ['GOOGLE_APPLICATION_CREDENTIALS']:
exit(-1)
creds, proj = google.auth.default()
request = {
'labelIds': ['INBOX'],
'topicName': 'projects/***PROJECTNAME***/topics/***TOPICNAME****'
}
delegated_credentials = creds.with_subject(TARGET_INBOX)
org_service = build('gmail', 'v1', credentials=delegated_credentials)
org_rval = None
try:
org_rval = org_service.users().watch(userId='me', body=request).execute()
except HttpError as err:
print("err={}, context={}".format(err, err.content))
except RefreshError as err:
print("err={}".format(err))
print("org_rval={}".format(org_rval))
return org_rval
【问题讨论】:
标签: gmail-api