如何解决PYTHON使用Gmail api / imaplib使用多个帐户登录
我目前正在处理需要gmail收件箱的应用程序。目前,我正在将Gmail API与certificate.json和token.pickle一起使用,尽管我希望每次使用脚本时都使用其他凭据登录,但此方法工作正常。我对这个API还是很陌生,想知道是否可以使用其他凭证(而不是用于token.pickle的凭证)登录。
Gmail API
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。