使用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
相关产品推荐
相关产品推荐

