Search code examples
python-3.xgmail-apigoogle-workspacegoogle-api-python-clientservice-accounts

Python, unable to send mail from google workspace mail address to individual gmail address


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:

  1. I added the recipient e-mail address to google workspace > Manage address lists
  2. I have activated the gmail api in the new project I created google cloud.
  3. I added 'google workspace e-mail address' to OAuth consent screen test users.
  4. In Authorized domains section of OAuth consent screen, I added the domain address that I received in the google workspace.
  5. In the Gmail scopes section of the OAuth consent screen, I granted the following permissions:
  • 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

  1. I choosed "actions admin" role for the service account
  2. I created a service account from the Create cerdientials section and saved the resulting key in json format where I ran the code

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?


Solution

  • 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