1

Based on this answer by @bossylobster, I have successfully implemented a cron job that connects with the GMail API. Currently I have the user_id and email address in my code, however I am building an app where it should run through a list of users.

Problem in that case is that when I run a loop on the CredentialsModel, I don't have the user's email address. Since I am using the User model from webapp 2 (based on this tutorial), I also can't look this ID up anywhere (as far as I know).

If I could somehow retrieve the email address with the user_id and credentials, or save the email address and user_id in the user model at the moment the permissions are given... What would be the best way to handle this?

My code for getting authorization:

http = httplib2.Http(memcache)
service = discovery.build("gmail", "v1", http=http)
decorator = OAuth2Decorator(client_id=settings.CLIENT_ID,
                        client_secret=settings.CLIENT_SECRET,
                        scope=settings.SCOPE)

class getPermissions(webapp2.RequestHandler):
  @decorator.oauth_aware
  def get(self):
    template_values = {
    'url': decorator.authorize_url(),
    'has_credentials': decorator.has_credentials()
    }
    self.response.out.write(template.render('templates/auth.html', template_values))
Community
  • 1
  • 1
Vincent
  • 1,137
  • 18
  • 40

2 Answers2

2

You can call the Gmail API with userId="me" which means, just use the userId of the authenticated user from the credential--don't need to specify an email address/userId. c.f. the description for the userId field in the docs: https://developers.google.com/gmail/api/v1/reference/users/labels/list

Eric D
  • 6,901
  • 1
  • 15
  • 26
  • Thanks, that will solve most of the problem. Nevertheless I'd like to know what user on my app matches with what credentials. Is it e.g. reliable / recommendable to save the user_id and do a google people API call directly on signup? – Vincent Apr 24 '15 at 19:17
2

Gmail API-specific method

You can call users.getProfile() to get an email address for the user:

user_profile = service.users().getProfile(userId='me').execute()
user_email = user_profile['emailAddress']

this method has the advantage of not requiring you to add any additional API scopes.

Generic Method

If you add email to your list of OAuth scopes, then your credentials object will include the user's email address:

try:
  print credentials.id_token['email']
except KeyError:
  print 'Unknown email'

See Google's docs for the email scope.

Jay Lee
  • 13,415
  • 3
  • 28
  • 59