Gmail API - 从 g-suite 服务帐户发送邮件时设置发件人姓名

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

我想动态更改显示在收件人邮箱中的名称(显示在主题左侧 + 电子邮件内容)。

无论我怎么尝试,名字总是以 'info' 结尾,'from' 地址总是 'info@g-suite-domain'

以下是我使用的代码。

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)

我试过了...

我通过以下方式获得了想要的结果:

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

我之前将域名提供商从 Wix 转移到 Namecheap,但我没有意识到 MX 记录没有转移。似乎,由于缺少 MX 记录,发件人地址将始终重写为 'info@g-suite-domain'(忽略消息 ['from'] 值)。