I have a webapp sending mail through the Gmail API using a service account that is impersonating a user account ([email protected]
) through domain-wide access.
The emails are sending fine, but the “From” fields of those emails are from [email protected]
. I want my emails to have a custom “From” field (say, "Custom From" <[email protected]>
).
However, specifying the “From” tag in my MIMEText message doesn’t change that the emails are sent with [email protected]
in the “From” field. I suspect when the service account impersonates the user account, it overrides the MIME message fields?
Below is the relevant code; I’m not sure how to override this behaviour.
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
SCOPES = ['https://www.googleapis.com/auth/gmail.send']
SERVICE_ACCOUNT_FILE = 'path/to/service/account/file.json'
creds = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)
creds = credentials.with_subject('[email protected]') ## The impersonation
service = build('gmail', 'v1', credentials=creds)
msg = MIMEMultipart('alternative')
msg.attach(MIMEText("<h1>Test message</h1>", 'html'))
msg.attach(MIMEText("Test message", 'plain'))
msg['Subject'] = 'Test subject'
msg['Bcc'] = '[email protected]'
msg['reply-to'] = '[email protected]' ## This is fine
msg['From'] = '"Custom From" <[email protected]>' ## The custom "From" field that gets overridden
create_message = {'raw': base64.urlsafe_b64encode(msg.as_bytes()).decode()}
service.users().messages().send(userId="me", body=create_message).execute()