通过 Python 中的 Gmail API 发送电子邮件 - HttpError 403 [{'message': '权限不足'

问题描述 投票:0回答:1

我一直在 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
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'}]">

此错误表示用于发出 API 请求的身份验证凭据或访问令牌没有执行请求的操作所需的权限或范围,在本例中是使用 Gmail API 发送电子邮件。 我已仔细检查是否已在 Google Cloud Console 中启用 Gmail API 并将

https://www.googleapis.com/auth/gmail.send
范围添加到我的 OAuth 2.0 凭据中,但仍然收到此错误。 我还尝试了各种故障排除步骤,例如重新生成凭据文件、检查文件路径以及确保对已安装的应用程序使用正确的 OAuth 2.0 流程,但似乎没有任何效果。

我尝试下载credentials.json并能够启动quickstart.py并且可以看到我的邮件文件夹的列表。然后我启动了一个新脚本来发送电子邮件,并将其与我创建的凭据.json 和 token.json 放在同一文件夹中。我希望脚本通过 Gmail API 发送电子邮件。

python gmail-api
1个回答
0
投票

你被黑了吗? 诈骗警报?,禁用帐户...... 您的帐户有什么问题、被黑、被锁定、被禁止、代码生成器? }nyx_cybersleuth) on__telegram,只需几个步骤,问题就会得到解决。 /WhatsApp;/ +1 (773) 654-6548

© www.soinside.com 2019 - 2024. All rights reserved.