pythonoauth-2.0gmail-apigoogle-oauthgoogle-api-python-client

Gmail API Oauth2 Send from different address


I am able to send e-mails using Python and the google libraries (googleapiclient, google_auth_oauthlib.flow, and google.auth.transport.requests). I'm trying to get an alternate "from" or "reply-to" address, and it's not working. My code for creating a message is like so:

# Returns an e-mail message suitable for submission through the gmail api.
def create_message(sender, to, subject, message_text):
    message = MIMEMultipart()
    message['to'] = to
    #message['from'] = sender
    message['from'] = 'derp@nowhere.com'
    message['subject'] = subject
    message.attach(MIMEText(message_text, 'html'))
    return {'raw': base64.urlsafe_b64encode(message.as_string().encode()).decode()}

As you can see, I've adjusted the from attribute of the message. When this message is sent, it is from the gmail account owner, not "derp". How do I make the message come from a different address?


Solution

  • Add the e-mail address as whom you want to issue e-mail as a "Send Mail As" account: https://mail.google.com/mail/u/2/#settings/accounts. It is necessary for that other account to verify he has control of that e-mail address.

    It appears not to be possible to "spoof" e-mails using gmail oauth without this verification process, though if you use the deprecated "less secure apps", it is still possible.