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

Python使用Google服务账号调用Gmail API遇401无效凭证错误求助

服务账号调用Gmail API返回401无效凭证问题

我正在编写一个需连接Google API下载邮件的脚本,该脚本将在服务器运行,因此需确保认证无需用户交互。根据官方文档建议,服务器到服务器应用应使用服务账号,我遵循教程操作后却返回401错误。

代码示例

from google.oauth2.service_account import Credentials
from googleapiclient.discovery import build
from typing import List, Dict
import logging


logging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO)


SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']
KEYWORD = "LinkedIn"


def login() -> Credentials:
    try:
        credentials = Credentials.from_service_account_file('credentials.json', scopes=SCOPES)
        return credentials

    except Exception as ex:
        logging.error(f"-----ERROR-----login: {ex}")
        



def get_unread_messages(credentials) -> List[Dict]:
    try:

        service = build('gmail', 'v1', credentials=credentials)

        result = service.users().messages().list(userId='me', labelIds=["INBOX", "UNREAD"]).execute()

        message_ids = result.get('messages')
        unread_messages = [service.users().messages().get(userId='me', id=msg['id']).execute() for msg in message_ids]

        return unread_messages

    except Exception as ex:
        logging.error(f"-----ERROR-----get_unread_messages:{ex}")

credentials = login()
get_unread_messages(credentials )

错误信息

------ERROR-----get_unread_messages:<HttpError 401 请求 https://gmail.googleapis.com/gmail/v1/users/me/messages?labelIds=INBOX&labelIds=UNREAD&alt=json 时返回 "请求包含无效的认证凭证。预期为OAuth 2访问令牌、登录Cookie或其他有效的认证凭证。"。详情: "[{'message': '无效凭证', 'domain': 'global', 'reason': 'authError', 'location': 'Authorization', 'locationType': 'header'}]">

问题原因及解决方法

  • 服务账号未配置域范围委派(仅Google Workspace账号适用)
    服务账号无法直接访问普通Gmail账号,若使用Google Workspace账号,需在Google Admin控制台给服务账号开启域范围委派,并指定要模拟的目标邮箱。修改凭证创建代码,添加subject参数:
    credentials = Credentials.from_service_account_file(
        'credentials.json',
        scopes=SCOPES,
        subject='目标邮箱@你的域名.com'
    )
    
  • userId参数错误
    服务账号模拟用户时不能用'me',需替换为实际要访问的邮箱地址。修改代码中两处userId='me'为目标邮箱,比如'user@example.com'。
  • Gmail API未启用
    登录Google Cloud控制台,确认已启用Gmail API。
  • 凭证文件问题
    检查credentials.json是否为服务账号的密钥文件,而非OAuth客户端ID文件,确保服务器能读取该文件,路径配置正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 10:55:02