import base64
from google.oauth2 import service_account
from googleapiclient.errors import HttpError
from googleapiclient.discovery import build
from googleapiclient import errors
from email.mime.text import MIMEText
# Authenticate with credentials from JSON file
creds = credentials
SCOPES = ['https://www.googleapis.com/auth/gmail.send']
SERVICE_ACCOUNT_FILE = 'C:/Users/Desktop/service-account-gmail-app.json'
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
# connect gmail api
service = build('gmail', 'v1', credentials=creds)
def send_email(service, to, subject, body, sender):
try:
message = create_message(to, subject, body, sender)
send_message(service, message)
print('E-mail was send successfully')
except HttpError as error:
print(f'E-mail was not sent: {error}')
def create_message(to, subject, body, sender):
message = MIMEText(body)
message['to'] = to
message['subject'] = subject
message['body'] = body
message['from'] = sender
return {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}
def send_message(service, message):
message = (service.users().messages().send(userId="me", body=message).execute())
to = 'individual gmail adress here'
subject = 'Test e-mail'
body = 'Hello this is a test message.'
sender='google workspace e-mail address here (including domain information) '
message = create_message(to, subject, body,sender)
print(message)
send_email(service, to, subject, body, sender)
The error:
E-mail was not sent: <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'}]">
Hello friends, I have done the following operations, but I cannot send an e-mail to my e-mail address if it is an individual from my google workspace account:
Gmail API .../auth/gmail.modify Read, compose and send emails from your Gmail account
Gmail API .../auth/gmail.compose Manage drafts and send emails
Gmail API .../auth/gmail.readonly View your email messages and settings
Why can't I send e-mails from my google workspace account to my personal e-mail address even though I have done these procedures? How will I solve the problem?
you need to deligate to a user on your domain
delegated_creds=credentials.with_subject("[email protected]
without domain wide deligation configured the service account doesn't have permission to send an email on the users behalf