Search code examples
pythonemailoauthgmailgmail-api

What is the best way to use the Google API to get just a user's email?


I'm writing a program with the gmail api and a problem I have run into is getting the currently authorized user's email address. I think I can do this with the scope https://www.googleapis.com/auth/userinfo.email as in http://www.hackviking.com/development/python-get-user-info-after-oauth/ but when I try that in Google's OAuth Playground it requests permission to "know who you are on Google" as well as permission to see your email address. The program doesn't need to know the user's name/info etc., it just needs the email address.

The reason I even am trying to use the userinfo.email scope is because after looking a while I can't find a way in the gmail scope to get the user's email but if there is a way that would be even better.


Solution

  • You could use the getProfile-method, and for that you need one of the following scopes:

    https://mail.google.com/
    https://www.googleapis.com/auth/gmail.modify
    https://www.googleapis.com/auth/gmail.compose
    https://www.googleapis.com/auth/gmail.readonly
    

    Then you can just get the email address:

    Request

    GET https://www.googleapis.com/gmail/v1/users/me/profile?fields=emailAddress&access_token={ACCESS_TOKEN}
    

    Response

    {
     "emailAddress": "[email protected]"
    }
    

    In Python this would look like:

    profile = gmail_service.users().getProfile(userId='me').execute()
    
    print 'Email address of user is: %s' % profile['emailAddress']