I am building a Python web application that sends emails via the Gmail API. I utilize a service account that has domain-wide access to impersonate a specific user ([email protected]
).
While the emails are sent without any issues, I want them to display a custom sender name, such as "Custom Sender" <[email protected]>
, instead of the impersonated user’s email address.
Whenever I attempt to assign a custom sender in the MIME message, it seems to be ignored, and the emails still reflect [email protected]
as the sender. It seems the API may be overriding the specified sender information due to the impersonation.
Is there a known method to define a different sender address when using a service account for impersonation? Are there built-in restrictions that are causing this behavior?
Below is my current code snippet:
import base64
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from googleapiclient.discovery import build
from google.oauth2 import service_account
# Load service account credentials
credentials = service_account.Credentials.from_service_account_file(
'path/to/credentials.json',
scopes=['https://www.googleapis.com/auth/gmail.send']
)
credentials = credentials.with_subject('[email protected]') # User impersonation
# Initialize Gmail service
service = build('gmail', 'v1', credentials=credentials)
# Create the email message
message = MIMEMultipart('alternative')
message.attach(MIMEText("<h1>Test email content</h1>", 'html'))
message.attach(MIMEText("Test email content", 'plain'))
message['Subject'] = 'Test Email Subject'
message['Bcc'] = '[email protected]'
message['Reply-To'] = '[email protected]' # This is accepted
message['From'] = '"Custom Sender" <[email protected]>' # This gets overridden
# Sending the email
raw_message = {'raw': base64.urlsafe_b64encode(message.as_bytes()).decode()}
service.users().messages().send(userId="me", body=raw_message).execute()
The email I receive states:
MIME-Version: 1.0
Reply-To: [email protected]
From: [email protected]