我正在构建python,用于检查10个电子邮件帐户的电子邮件,但是在google文档中并不是很有用。这似乎只支持一个帐户https://github.com/suleenwong/Gmail-API-Python。
发布于 2022-09-04 10:36:31
如果我们检查默认的示例python快速启动,则此示例设计为单个用户,但可以更改。
以下部分在用户授权应用程序时创建一个token.json文件。该文件将包含授权代码的用户的访问令牌和刷新令牌。
如果该文件不存在,则应用程序将提示用户授权它。如果是这样的话,应用程序将从该文件加载凭据,并在用户的授权下运行代码。
# The file token.json 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.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# 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.json', 'w') as token:
token.write(creds.to_json())要添加更多用户,只需重命名该文件tokenUserOne.json,tokenUserTwo.json。然后设置它,以便提供要运行脚本的文件名。您只需要授权每个用户一次。只要您为每个用户分离了一个token.json文件,您的应用程序就可以开始使用您想要的令牌文件来访问每个用户的数据。
发布于 2022-09-02 15:16:11
https://developers.google.com/gmail/api/quickstart/python -this是您需要的适当文档。
aka (您还需要一个client_secet.json文件,但是您必须为google获取自己):
from __future__ import print_function
import os.path
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
# If modifying these scopes, delete the file token.json.
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.json 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.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# 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.json', 'w') as token:
token.write(creds.to_json())
try:
# Call the Gmail API
service = build('gmail', 'v1', credentials=creds)
results = service.users().labels().list(userId='me').execute()
labels = results.get('labels', [])
if not labels:
print('No labels found.')
return
print('Labels:')
for label in labels:
print(label['name'])
except HttpError as error:
# TODO(developer) - Handle errors from gmail API.
print(f'An error occurred: {error}')
if __name__ == '__main__':
main()https://stackoverflow.com/questions/73584575
复制相似问题