Search code examples
pythongmail-apigoogle-workspaceservice-accounts

Gmail API - set sender name when sending mail from a g-suite service account


I want to dynamically change the name that shows up in the recipients mailbox (appears on the left of the subject + content of the email).

No matter what I try, the name always ends up as 'info', and the 'from' address is always 'info@g-suite-domain'

Following is the code I'm using.

import argparse
import base64
import os
import sys
from email.mime.text import MIMEText
from apiclient import errors
from google.oauth2 import service_account
from googleapiclient.discovery import build
from httplib2 import Http


def create_message(sender, to, subject, message_text):
    """Create a message for an email.
    Args:
      sender: Email address of the sender.
      to: Email address of the receiver.
      subject: The subject of the email message.
      message_text: The text of the email message.
    Returns:
      An object containing a base64url encoded email object.
    """
    message = MIMEText(message_text, 'html')
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject
    raw = base64.urlsafe_b64encode(message.as_bytes())
    raw = raw.decode()
    body = {'raw': raw}
    return body


def send_message(service, user_id, message):
    """Send an email message.
    Args:
      service: Authorized Gmail API service instance.
      user_id: User's email address. The special value "me"
      can be used to indicate the authenticated user.
      message: Message to be sent.
    Returns:
      Sent Message.
    """
    try:
        message = (service.users().messages().send(userId=user_id, body=message)
                   .execute())
        print('Message Id: %s' % message['id'])
        return message
    except errors.HttpError as error:
        print('An error occurred: %s' % error)


def service_account_login():
    SCOPES = [
        'https://mail.google.com',
        'https://www.googleapis.com/auth/gmail.compose',
        'https://www.googleapis.com/auth/gmail.modify',
        'https://www.googleapis.com/auth/gmail.readonly',
    ]

    dirname = os.path.dirname(os.path.realpath(__file__))
    SERVICE_ACCOUNT_FILE = dirname + '/service-key.json'

    credentials = service_account.Credentials.from_service_account_file(
        SERVICE_ACCOUNT_FILE, scopes=SCOPES)
    delegated_credentials = credentials.with_subject(
        'info@g-suite-domain')
    service = build('gmail', 'v1', credentials=delegated_credentials)
    return service


if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--to', required=True)
    parser.add_argument('--subject', required=True)
    args = parser.parse_args()
    content = sys.stdin.read()

    EMAIL_FROM = "service-acount-id@project-id.iam.gserviceaccount.com"

    service = service_account_login()
# Call the Gmail API
    message = create_message(EMAIL_FROM, args.to, args.subject, content)
    sent = send_message(service, 'me', message)

I have tried...

  • relevant solutions I could find online but none helped.
  • setting both the EMAIL_FROM and with_subject address to the form of "Name <sender-address@domain>" which has no effect.
  • changing the 'Send mail as' option in gmail for 'info@g-suite-domain'
  • specifying the name for both email accounts in gmail, google admin, and google console.
  • creating a new project + service account
  • reading the googleapiclient.discovery library for problematic code but could not find anything.

Solution

  • I previously transferred the domain providers from Wix to Namecheap, and I didn't realize the MX records were not transferred. It seems, due to the lack of MX record, the from address would always rewrite to 'info@g-suite-domain' (ignoring the message['from'] value).