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

使用Python脚本通过Gmail API服务账号发送邮件遇前置检查失败问题

使用Google Workspace服务账号发送邮件的Python脚本问题

背景

  • 已创建ServiceAccount及其JSON格式密钥
  • 在Google Workspace的API控制台中,为该ServiceAccount(通过唯一ID)配置了https://www.googleapis.com/auth/gmail.send权限

初始Python脚本

import base64
from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials

scope_gmail_api = ['https://www.googleapis.com/auth/gmail.send']
authentication_credential = "credential.json"

def create_email(subject, message_text, to, from_email):
    message = f"From: {from_email}\nSubject: {subject}\nTo: {to}\n\n{message_text}"
    return {'raw': base64.urlsafe_b64encode(message.encode("utf-8")).decode("utf-8")}

def create_email_service():
    creds = None
    creds = ServiceAccountCredentials.from_json_keyfile_name(
    authentication_credential, scope_gmail_api)

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

gmail_service = create_email_service()

def main():

    subject = "Test Subject"
    message_text = "Test"
    to_email = "destination@domain.com"
    from_email = "source@domain.com"
    message = create_email(subject, message_text, to_email, from_email)

    try:
        sent_message = gmail_service.users().messages().send(userId='me', body=message).execute()
        print(f'E-mail sent: Message ID: {sent_message["id"]}')
    except Exception as e:
        print(f'Error: {str(e)}')

if __name__ == '__main__':
    main()

运行后错误

Error: <HttpError 400 when requesting https://gmail.googleapis.com/gmail/v1/users/me/messages/send?alt=json returned "Precondition check failed.". Details: "[{'message': 'Precondition check failed.', 'domain': 'global', 'reason': 'failedPrecondition'}]">

尝试权限委托后的错误

参考相关评论尝试添加delegated_credentials = creds.with_subject('admin@mydomain.com'),出现以下错误:

AttributeError: 'ServiceAccountCredentials' object has no attribute 'with_subject'

更新代码后的尝试及错误

改用以下代码实现权限委托:

credentials = service_account.Credentials.from_service_account_file(
        authentication_credential, scopes=scope_gmail_api)

delegated_credentials = credentials.with_subject('admin@mydomain.com')

但仍出现相同的预检查失败错误:

ERROR: <HttpError 400 when requesting https://gmail.googleapis.com/gmail/v1/users/me/messages/send?alt=json returned "Precondition check failed.". Details: "[{'message': 'Precondition check failed.', 'domain': 'global', 'reason': 'failedPrecondition'}]">

疑问

我遗漏了什么?


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 10:16:28