macOS下Python调用Gmail API发邮件遇HttpError 403权限不足问题
问题:Gmail API发送邮件返回403权限不足错误
我在macOS上开发Python脚本调用Gmail API发送邮件,按官方文档操作后始终报错,具体情况如下:
代码示例
from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError import base64 from email.mime.text import MIMEText import os # 补充原代码遗漏的导入 SCOPES = ['https://www.googleapis.com/auth/gmail.send'] def send_email(sender, recipient, subject, body): 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()) try: service = build('gmail', 'v1', credentials=creds) message = MIMEText(body) message['to'] = recipient message['from'] = sender message['subject'] = subject encoded_message = base64.urlsafe_b64encode(message.as_bytes()).decode() create_message = {'raw': encoded_message} send_message = service.users().messages().send(userId='me', body=create_message).execute() print(f'Message Id: {send_message["id"]}') except HttpError as error: print(f'An error occurred: {error}')
报错信息
<HttpError 403 when requesting https://gmail.googleapis.com/gmail/v1/users/me/messages/send?alt=json returned "Request had insufficient authentication scopes.". Details: "[{'message': 'Insufficient Permission', 'domain': 'global', 'reason': 'insufficientPermissions'}]">
已执行的排查操作
- 确认Google Cloud Console中已启用Gmail API
- 为OAuth 2.0凭据配置了
https://www.googleapis.com/auth/gmail.send权限范围 - 重新生成
credentials.json并确认文件路径正确 - 使用官方推荐的安装应用OAuth 2.0流程
- 此前用同一
credentials.json运行quickstart.py可正常查看邮件文件夹列表,当前脚本与credentials.json、token.json在同一目录
解决方法
问题根源是之前运行quickstart.py生成的token.json仅包含只读类权限,新脚本虽指定了发送权限,但程序会优先加载已存在的旧token,导致权限不足。
解决步骤:
- 删除当前目录下的
token.json文件 - 重新运行发送邮件脚本,按提示完成OAuth授权,生成包含
gmail.send权限的新token.json - 再次执行发送操作即可正常运行
另外,注意补充原代码中遗漏的import os语句,避免因未导入模块引发额外错误。
内容的提问来源于stack exchange,提问作者Kate Throw
相关产品推荐
相关产品推荐

