PYTHON使用Gmail api / imaplib使用多个帐户登录

问题描述

我目前正在处理需要gmail收件箱的应用程序。目前,我正在将Gmail API与certificate.json和token.pickle一起使用,尽管我希望每次使用脚本时都使用其他凭据登录,但此方法工作正常。我对这个API还是很陌生,想知道是否可以使用其他凭证(而不是用于token.pickle的凭证)登录。

Gmail API

要获取当前的Gmail收件箱,请使用以下代码:

    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)

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

Imaplib

我尝试获取特定用户的收件箱的另一种方法是使用imaplib和电子邮件库,因为它允许您使用特定的电子邮件地址和密码登录。但是,要使其正常工作,用户需要允许安全程度较低的应用访问其Google帐户,这对每个用户启用该应用都是麻烦。我用于imaplib的代码是以下代码:

import imaplib,email


username = 'USERNAME'
password = 'PASSWORD'
imap_url = 'imap.gmail.com'


con = imaplib.IMAP4_SSL(imap_url)

con.login(username,password)

con.select('Inbox')

问题

我的问题是:是否可以使用Google的gmail api使用多个/其他凭据登录以获得相应的gmail收件箱?如果这不可能并且我必须使用Imaplib方式,那么我需要采取什么步骤,以免用户启用安全性较低的应用?

解决方法

只需更改.pickle文件名。可能的代码仅更改user变量即可完成此操作。每个帐户都有不同的令牌

def api_connection(user):
    scopes = ['https://www.googleapis.com/auth/gmail.readonly']
    creds = None
    if os.path.exists(f'{user}.pickle'):
        with open(f'{user}.pickle','rb') as token:
            creds = pickle.load(token)
    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)
        with open(f'{user}.pickle','wb') as token:
            pickle.dump(creds,token)
    service = build('gmail','v1',credentials=creds)
    return service

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...