【发布时间】:2015-06-25 02:21:32
【问题描述】:
我有一个适用于 Google 邮件的 IMAP 客户端,但它最近停止工作。我相信问题是gmail不再允许TTL用户名/密码登录,但现在需要OAuth2.0。
我想知道更改下面示例的最佳方法,以便我的扭曲 IMAP 客户端使用 OAuth2.0 进行身份验证。 (如果可能的话,在没有 Google API 包的情况下这样做。)
使用用户名/密码登录的示例(不再有效)
class AriSBDGmailImap4Client(imap4.IMAP4Client):
'''
client to fetch and process SBD emails from gmail. the messages
contained in the emails are sent to the AriSBDStationProtocol for
this sbd modem.
'''
def __init__(self, contextFactory=None):
imap4.IMAP4Client.__init__(self, contextFactory)
@defer.inlineCallbacks
def serverGreeting(self, caps):
# log in
try:
# the line below no longer works for gmail
yield self.login(mailuser, mailpass)
try:
yield self.uponAuthentication()
except Exception as e:
uponFail(e, "uponAuthentication")
except Exception as e:
uponFail(e, "logging in")
# done. log out
try:
yield self.logout()
except Exception as e:
uponFail(e, "logging out")
@defer.inlineCallbacks
def uponAuthentication(self):
try:
yield self.select('Inbox')
try:
# read messages, etc, etc
pass
except Exception as e:
uponFail(e, "searching unread")
except Exception as e:
uponFail(e, "selecting inbox")
我为这个客户提供了一个简单的工厂。它通过使用 reactor.connectSSL 与 Google 邮件的主机 url 和端口开始。
我已经按照https://developers.google.com/gmail/api/quickstart/quickstart-python 的指示进行了“已安装的应用程序”(但我不知道这是否是正确的选择)。我可以成功运行他们的“quickstart.py”示例。
我快速而肮脏的尝试(不起作用)
@defer.inlineCallbacks
def serverGreeting(self, caps):
# log in
try:
#yield self.login(mailuser, mailpass)
flow = yield threads.deferToThread(
oauth2client.client.flow_from_clientsecrets,
filename=CLIENT_SECRET_FILE,
scope=OAUTH_SCOPE)
http = httplib2.Http()
credentials = yield threads.deferToThread( STORAGE.get )
if credentials is None or credentials.invalid:
parser = argparse.ArgumentParser(
parents=[oauth2client.tools.argparser])
flags = yield threads.deferToThread( parser.parse_args )
credentials = yield threads.deferToThread(
oauth2client.tools.run_flow,
flow=flow,
storage=STORAGE,
flags=flags, http=http)
http = yield threads.deferToThread(
credentials.authorize, http)
gmail_service = yield threads.deferToThread(
apiclient.discovery.build,
serviceName='gmail',
version='v1',
http=http)
self.state = 'auth'
try:
yield self.uponAuthentication()
except Exception as e:
uponFail(e, "uponAuthentication")
except Exception as e:
uponFail(e, "logging in")
# done. log out
try:
yield self.logout()
except Exception as e:
uponFail(e, "logging out")
我基本上只是将“quickstart.py”复制到serverGreeting,然后尝试将客户端状态设置为“auth”。
这个验证就好了,但是twisted无法选择收件箱:
[AriSBDGmailImap4Client (TLSMemoryBIOProtocol),client] FAIL: Unknown command {random gibberish}
随机乱码有字母和数字,每次选择收件箱命令失败时都是不同的。
感谢您的帮助!
【问题讨论】:
标签: python oauth-2.0 gmail google-oauth twisted