GCP Gmail API: How to send an email programmatically from a compute engine instance using Python

319 Views Asked by At

Description: Hi All, I am trying to send an email using a Python script inside a compute engine VM. When I enabled the Gmail API, I was asked to create Gmail API credentials it then gave me mutliple options to choose from, so I picked the option with description "Enables server-to-server, app-level authentication using robot accounts", which seems have enabled the compute engine service account to be used for authentication

What I tried: I tried to follow https://developers.google.com/gmail/api/quickstart/python but it seems the page describes the autentication using OAuth client via UI, which can't work since the script should be running programmatically.

Also I made a trial using the code below

import base64
from google.oauth2 import service_account
from googleapiclient.discovery import build

# Load credentials from JSON file
credentials = service_account.Credentials.from_service_account_file('path/to/compute_engine_key.json')

# Create Gmail API client
service = build('gmail', 'v1', credentials=credentials)

# Define email details
sender = "[email protected]"
recipient = "[email protected]"
subject = "test"
message = "test"

# Build the email message
email = (
    f"From: {sender}\n"
    f"To: {recipient}\n"
    f"Subject: {subject}\n\n"
    f"{message}"
)

# Send the email
message = service.users().messages().send(
    userId='me',
    body={'raw': base64.urlsafe_b64encode(email.encode()).decode()}
).execute()

print("Email sent! Message ID:", message['id'])

But I got this error: googleapiclient.errors.HttpError: <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'}]">

Could someone kindly offer guidance on the appropriate method to make this work?. Thanks

0

There are 0 best solutions below