Send Emails via Gmail API in Python - HttpError 403 [{'message': 'Insufficient Permission'

49 Views Asked by At

I've been working on a Python script in macOS to send emails using the Gmail API, but I'm running into some issues that I can't seem to resolve. I've followed the official documentation and examples, but I keep getting errors when trying to send the email. Here's a simplified version of my code (with personal information removed):

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}')

The main issue I'm facing is the following 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'}]">

This error indicates that the authentication credentials or access token used to make the API request do not have the necessary permissions or scopes to perform the requested action, which in this case is sending an email using the Gmail API. I've double-checked that I've enabled the Gmail API in the Google Cloud Console and added the https://www.googleapis.com/auth/gmail.send scope to my OAuth 2.0 credentials, but I'm still getting this error. I've also tried various troubleshooting steps, such as regenerating the credentials file, checking the file paths, and ensuring that I'm using the correct OAuth 2.0 flow for installed applications, but nothing seems to work.

I tried to download the credentials.json and was able to start quickstart.py and could see the listing of my mail folder. Then I started a new script to send an email and put it in the same folder together with the credentials.json and token.json I created. I expected the script to send an email via Gmail API.

0

There are 0 best solutions below