如何在Python Gmail API中更改Sender的名称?

时间:2018-05-23 15:49:45

标签: python gmail-api

我正在编写一个脚本,当我得到新成绩时,会给我发电子邮件。一切都很完美,除了发件人显示为我的电子邮件......

from __future__ import print_function
from apiclient.discovery import build
from httplib2 import Http
from oauth2client import file, client, tools
from email.mime.text import MIMEText
import base64

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)
    message['to'] = to
    message['from'] = sender
    message['subject'] = subject
    return {'raw': base64.urlsafe_b64encode(message.as_string().encode("utf-8")).decode()}


def send_message(message):
    global service
    user_id = "me"
    """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())
        return message
    except exception as error: # I am aware this line is broken, but it does goes through successfully so this does not execute
        print('An error occurred: %s' % error)


# Setup the Gmail API
SCOPES = 'https://www.googleapis.com/auth/gmail.send'
store = file.Storage('credentials.json')
creds = store.get()
if not creds or creds.invalid or creds == "None":
    flow = client.flow_from_clientsecrets('client_secret.json', SCOPES)
    creds = tools.run_flow(flow, store)
service = build('gmail', 'v1', http=creds.authorize(Http()))

msg = create_message("fname lname", "to@email.com", '', content)
send_message(msg)

这是我发送邮件的代码,但是当我发送邮件时,我的电子邮件显示为发件人...如何解决此问题?

(我已尝试将发件人设为"John Smith" <from@email.com>John Smith <from@email.com>

2 个答案:

答案 0 :(得分:0)

使用以下代码:

sender = 'John Smith <from@email.com>'
receiver = 'sample@email.com'
subject = 'Subject'
message_text = 'Example of message'

message = create_message(sender, receiver, subject, message_text)

答案 1 :(得分:0)

我只是通过设置mail选项使其在ruby中工作:

from: "'some name' <#{variable_of_email_string}>"