python - 根据 user_id 获取 Google 帐户电子邮件地址

标签 python google-app-engine gmail-api

基于 this answer通过@bossylobster,我已经成功地实现了一个与 GMail API 连接的 cron 作业。目前我的代码中有 user_id 和电子邮件地址,但是我正在构建一个应用程序,它应该在用户列表中运行。

这种情况下的问题是,当我在 CredentialsModel 上运行循环时,我没有用户的电子邮件地址。由于我使用的是 webapp 2 中的用户模型(基于 this tutorial ),因此我也无法在任何地方查找此 ID(据我所知)。

如果我能以某种方式检索带有 user_id 和凭据的电子邮件地址,或者在授予权限时将电子邮件地址和 user_id 保存在用户模型中...处理此问题的最佳方法是什么?

我获取授权的代码:

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))

最佳答案

特定于 Gmail API 的方法

您可以调用users.getProfile()获取用户的电子邮件地址:

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

此方法的优点是不需要您添加任何额外的 API 范围。

通用方法

如果您将 email 添加到您的 OAuth 范围列表,那么您的凭据对象将包含用户的电子邮件地址:

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

参见 Google's docs for the email scope .

关于python - 根据 user_id 获取 Google 帐户电子邮件地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29849051/

相关文章:

python - 是否可以在 IPython Notebook 中创建输入单元格分组?

python - 如何将 Pandas 中的特定列拆分为新列?

python - pip 从 github 安装 python 应用程序,不依赖 pypi

java - 在应用程序引擎中过滤记录 (Java)

google-app-engine - gae 每月最后一天的 cron 作业

python - 升级后pip坏了

python - 在 Google App Engine Python 沙箱中调试

gmail-api - 查找使用 gmail api 检索的环聊和聊天消息的时间戳

java - 为什么 Gmail API ListThreadResponse get Threads 没有做任何事情?

php - 使用 gmail api 发送电子邮件时等号丢失