首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Gmail :如何简单地对用户进行身份验证并获取他们的消息列表?

Gmail :如何简单地对用户进行身份验证并获取他们的消息列表?
EN

Stack Overflow用户
提问于 2021-01-13 04:42:44
回答 1查看 1.4K关注 0票数 2

我试图构建一个简单的python脚本来访问gmail的API,并将收件箱中的某些电子邮件消息组织到一个csv文件中。

我在下面的文档中看到,访问消息使用的是用户的电子邮件地址(在本例中是我的)。

messages.list

我在访问API时遇到了困难。我得到了以下错误:

“请求缺少所需的身份验证凭据。预期的OAuth 2访问令牌、登录cookie或其他有效的身份验证凭据。请参见https://developers.google.com/identity/sign-in/web/devconsole-project."

我希望构建一个轻量级的脚本,而不是一个web应用程序。有没有人知道我是否可以在脚本中验证我自己的电子邮件地址?

PS:我想我可以使用selenium自动登录,但是我想知道是否有一种方法可以使用gmail的API来实现。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-01-13 06:39:21

您需要了解您要访问的数据是私有用户数据。这是用户所拥有的数据,这意味着您的应用程序需要得到用户“您”的“授权”才能访问他们的数据。

我们使用一种名为Oauth2的方法来实现这一点,它将允许您的应用程序请求用户同意访问,以便在本例中读取用户电子邮件。

为了使用Oauth2,您必须首先在控制台上注册您的应用程序并设置一些内容,这将标识您的应用程序到谷歌。

所有这些都在gmail的Python快速启动中进行了解释。一旦完成了这一任务,您应该能够更改代码以使用message.list而不是labels.list。

代码语言:javascript
运行
复制
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly']

def main():
    """Shows basic usage of the Gmail API.
    Lists the user's Gmail labels.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('gmail', 'v1', credentials=creds)

    # Call the Gmail API
    results = service.users().labels().list(userId='me').execute()
    labels = results.get('labels', [])

    if not labels:
        print('No labels found.')
    else:
        print('Labels:')
        for label in labels:
            print(label['name'])

if __name__ == '__main__':
    main()
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65695786

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档