【问题标题】:What is the best way to use the Google API to get just a user's email?使用 Google API 获取用户电子邮件的最佳方式是什么?
【发布时间】:2016-05-23 23:51:11
【问题描述】:

我正在使用 gmail api 编写一个程序,我遇到的一个问题是获取当前授权用户的电子邮件地址。我想我可以使用https://www.googleapis.com/auth/userinfo.email 的范围来做到这一点,就像http://www.hackviking.com/development/python-get-user-info-after-oauth/ 一样,但是当我在 Google 的 OAuth Playground 中尝试这样做时,它会请求“知道您在 Google 上的身份”的权限以及查看您的电子邮件地址的权限。该程序不需要知道用户的姓名/信息等,它只需要电子邮件地址。

我什至尝试使用 userinfo.email 范围的原因是,经过一段时间后,我无法在 gmail 范围内找到获取用户电子邮件的方法,但如果有更好的方法。

【问题讨论】:

    标签: python email oauth gmail gmail-api


    【解决方案1】:

    您可以使用getProfile-方法,为此您需要以下范围之一:

    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
    

    然后你就可以得到邮箱地址了:

    请求

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

    回应

    {
     "emailAddress": "foo@gmail.com"
    }
    

    在 Python 中,这看起来像:

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

    【讨论】:

    • 非常感谢,这正是我想要的。只是另一个问题,你知道我是否有办法在 Python 中只使用 api 来做到这一点,还是我需要使用 httplib 或其他东西来处理 GET 请求?
    • @sj-f 没问题! Gmail API Client Library for Python 中有一个方法,如果您不介意获取整个 Profile,而不仅仅是 emailAddress。但数据不多,所以应该很好用。
    • 再次感谢我现在可以正常工作,但我遇到了另一个问题。现在我有了address = gmail_service.users().getProfile(userId='me'),我尝试将其解析为 JSON,但控制台告诉我这是 HTTPRequest 类型的对象,我不能将其用作 json.load() 的参数。 api 文档说它返回一个具有这些属性的对象,但我不知道如何从请求中获取对象。
    • @sj-f 编辑了答案。
    • @sj-f 没问题 :) 祝你的程序好运!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-07
    • 2011-06-18
    • 1970-01-01
    • 2014-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多