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

使用Google API Python客户端配置Email Audit时的权限与初始化问题

关于Google Email Audit API Python客户端配置的问题

我参考googleapis GitHub上的代码示例学习Email Audit API的用法,示例用sample_tools.init初始化服务并指定了只读scope。因为需要读写权限,我改用build方法初始化并设置了读写scope,但遇到两个问题:

  1. 无效scope错误:使用管理员账号授权时提示:

Authorization Error
Error 400:
invalid_scope
Some requested scopes cannot be shown: [https://www.googleapis.com/auth/apps.reporting.audit]

  1. API名称/版本未知错误:用只读scope测试时,出现:

googleapiclient.errors.UnknownApiNameOrVersion: name: audit version: v1

想请教如何正确配置邮件监控,同时确认这个GitHub示例是否已过时?


问题分析与解决

1. 无效scope问题

Email Audit API的读写scope并非你使用的https://www.googleapis.com/auth/apps.reporting.audit,正确的权限scope如下:

  • 读写权限:https://www.googleapis.com/auth/admin.audit.mail
  • 只读权限:https://www.googleapis.com/auth/admin.audit.mail.readonly

你之前用的是旧命名规范的scope,早已失效,替换为上述正确scope即可解决授权时的invalid_scope错误。

2. API名称/版本错误

Email Audit API属于Admin SDK的一部分,并非独立的audit服务。使用build方法时,需要指定服务名为admin、版本为directory_v1,再通过对应端点访问Audit功能。

正确的服务初始化代码示例:

from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
import os

# 使用正确的读写scope
SCOPES = ['https://www.googleapis.com/auth/admin.audit.mail']

creds = None
if os.path.exists('token.json'):
    creds = Credentials.from_authorized_user_file('token.json', SCOPES)
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file(
            'credentials.json', SCOPES)
        creds = flow.run_local_server(port=0)
    with open('token.json', 'w') as token:
        token.write(creds.to_json())

# 正确初始化Admin SDK服务
admin_service = build('admin', 'directory_v1', credentials=creds)
# 示例:获取邮件监控配置
audit_configs = admin_service.customer().audit().list(customerId='my_customer').execute()

关于GitHub示例的有效性

你参考的那个示例确实已经过时:

  • 它使用的audit服务名称和旧scope均已被弃用
  • 当前Email Audit API已整合到Admin SDK Directory API中,所有操作必须通过Admin SDK的端点调用

额外注意事项

  • 必须使用Google Workspace管理员账号授权,普通账号无权限访问Email Audit API
  • 在Google Cloud控制台中,需要启用Admin SDK API(而非独立的Audit API)
  • OAuth 2.0客户端ID需配置为「桌面应用」类型,避免授权流程出错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 23:50:32