0
votes

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 = "[email protected]"

    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.
2
delegated_credentials = credentials.with_subject( 'info@g-suite-domain') <-- thats becouse thats the user your telling it to use.DaImTo
@DaImTo I understand, but how can I change the sender name? I even tried changing the 'Send mail as' option to no avail.t-wilkinson
info@g-suite-domain is a User in your domain, go to the domain and change the name. You could also try changing EMAIL_FROMDaImTo
@DaImTo I updated the question, but I did try changing the name (gmail, google console, and google admin). What do you mean by changing EMAIL_FROM? I've tried variations specified by rfc 2822, but nothing seems to have any effect.t-wilkinson
Sorry im kind of going on memory i dont have access to gsuite anymore so i cant test it using service accounts. it has a lot to do with the fact that you are deligationg to that user which from what i remember the name is going to be that users name.DaImTo

2 Answers

1
votes

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).

0
votes

I have obtained the desired result with:

message["from"] = "info@g-suite-domain <info@g-suite-domain>"