python - Gmail API:如何简单地验证用户并获取他们的邮件列表?
问题描述
我正在尝试构建一个简单的 python 脚本来访问 gmail 的 API 并将我的收件箱中的某些电子邮件信息组织到一个 csv 文件中。
我在下面的文档中看到,访问消息是使用用户(在这种情况下是我的)电子邮件地址完成的。
我在访问 API 时遇到了困难。我收到以下错误:
“请求缺少所需的身份验证凭据。需要 OAuth 2 访问令牌、登录 cookie 或其他有效的身份验证凭据。请参阅https://developers.google.com/identity/sign-in/web/devconsole-project。”
我希望构建一个轻量级脚本而不是 Web 应用程序。有谁知道是否有一种方法可以在脚本中验证我自己的电子邮件地址?
PS:我想我可以使用 selenium 自动登录,但我想知道是否有办法使用 gmail 的 API 来做到这一点。
解决方案
您需要了解您尝试访问的数据是私人用户数据。这是属于您的用户所拥有的数据,这意味着您的应用程序需要得到用户“您”的“授权”才能访问他们的数据。
我们使用称为 Oauth2 的方法来执行此操作,在这种情况下,它将允许您的应用程序请求同意访问以读取用户的电子邮件。
为了使用 Oauth2,您必须首先在Google Developer Console上注册您的应用程序并设置一些东西,这将向 Google 识别您的应用程序。
所有这些都在gmail的Python 快速入门中进行了解释。一旦你完成了这项工作,你应该能够将代码更改为使用 message.list 而不是 labels.list。
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()
推荐阅读
- nestjs - 如何在带有嵌套会话的守卫中使用会话对象
- javascript - 使用 setTimeout 重新加载 Ajax 函数不会首先清除先前的超时
- python - 如何使用 struct.unpack 从 python 3 中的字节列表中提取 int?
- python - Celery 不适用于 Heroku 上的 Django。获取`Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection denied`错误
- selenium - 在 Python 中使用 webdriver 抓取时,通过“单击”“显示更多”来扩展显示的表格
- c# - 如何为字节添加前缀(1)?
- c++ - 计算文件c ++中的大写字母
- javascript - 打字稿 - 转发和用户引用
- django - 在 Django Rest Framework 中测试 CSRF 保护视图
- python - 合并多个熊猫帧