You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用服务账号调用Gmail API遇unauthorized_client错误求助

解决 unauthorized_client: Client is unauthorized to retrieve access tokens using this method 错误

我之前遇到过完全一样的问题,很快就定位到了问题根源——你的代码里没有把权限范围(scopes)和委派用户(subject)合并到同一个凭证对象中,导致服务账号凭证缺少访问Gmail API的必要权限,最终触发了这个授权错误。

具体出错点分析

你创建了scoped_credentials来添加https://mail.google.com/的权限范围,但后续并没有使用这个带权限的凭证,而是直接用原始的无权限范围的credentials调用with_subject生成委派凭证。这样的凭证自然没有权限请求Gmail API的访问令牌。

修正后的代码

把权限范围和委派用户的配置合并到同一个凭证流程里即可解决问题:

""" Sample program """
import googleapiclient.discovery
import json
import googleapiclient.errors
from google.oauth2 import service_account

SERVICE_ACCOUNT_FILE = 'abcd.json'
# 加载服务账号凭证时直接指定所需的scopes
credentials = service_account.Credentials.from_service_account_file(
    SERVICE_ACCOUNT_FILE,
    scopes=['https://mail.google.com/']
)
# 基于带权限范围的凭证添加委派用户
delegated_credentials = credentials.with_subject('abcd')
service = googleapiclient.discovery.build('gmail','v1',credentials = delegated_credentials)

try:
    results = service.users().labels().list(userId='abcd').execute()
    print(results)
except Exception as err:
    print(err)

额外检查点(如果修正后仍报错)

  • 确认在Admin Console的「Manage API Access」中,给服务账号授权的scope完全匹配https://mail.google.com/,不要有拼写或格式错误
  • 确认with_subject里的abcd是你的Google Workspace域内的有效用户邮箱(比如完整格式user@yourdomain.com)
  • 确认服务账号已经正确开启域范围委派(Domain Wide Delegation),且对应的客户端ID已在Admin Console中完成登记

内容的提问来源于stack exchange,提问作者Shilpa Yellapragada

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 07:05:22