2011-11-01 59 views
1

我试图从我的web应用程序启用Gmail IMAP访问。目前,用户可以授予对Web应用程序的访问权,成功检索并存储用户的令牌和秘密。但是,当我尝试检索电子邮件的IMAP连接进行身份验证,它提供了以下错误:Gmail IMAP身份验证 - imaplib.authenticate只需3个参数(4个给定)

TypeError: authenticate() takes exactly 3 arguments (4 given) 

下面是代码(很简单):

import oauth2 as oauth 
import imaplib 

consumer = oauth.Consumer('token','secret') 
token = oauth.Token('token','secret') 

url = "https://mail.google.com/mail/b/[email protected]/imap/" 
conn = imaplib.IMAP4_SSL('imap.googlemail.com') 
conn.debug = 4 
conn.authenticate(url,consumer,token) 

我试着打了退堂鼓一点点避免实际authenticate功能,但无济于事:

imaplib.IMAP4_SSL.authenticate(conn,'XOAUTH',lambda x: oauth.build_xoauth_string(url,consumer,token)) 

这给了我类似的输出:

29:03.17 > CMIK6 AUTHENTICATE XOAUTH 
29:03.27 < CMIK5 BAD Too many arguments provided s68if10067716yhm.26 
29:03.27 BAD response: Too many arguments provided s68if10067716yhm.26 

我不确定问题可能是什么。为什么authenticate函数会认为有4个参数? oauth字符串是否可以解释为多个字符串,即不能正确转义?他们有斜线,下划线,加号​​,但没有逗号。

还有其他想法吗?

+2

您是否尝试过使用oauth2 imaplib包装? '输入oauth2.clients.imap作为imaplib' – Acorn

+1

'authenticate'是'conn'的一种方法,'self'是第一个参数,我想。 – kev

+0

@Acorn似乎已经做到了。我仍然在玩这个游戏,不过无论出于何种原因,它并没有抛出同样的错误。 – tchaymore

回答

2

当使用OAuth2以IMAP,您需要将它与oauth2.clients.imap结合使用,所以:

import oauth2 as oauth 
import oauth2.clients.imap as imaplib 

# the rest of your code as it was 

您可以在此页面底部看到一个示例:https://github.com/simplegeo/python-oauth2

1

authenticate方法只需要2个参数(如果包含self,则为3)。这article解释它如何工作(文档不是很有帮助)。

你的第二次尝试看起来很有希望,如果你只是提供2个ARGS:

conn.authenticate('XOAUTH',lambda x: oauth.build_xoauth_string(url,consumer,token)) 

希望有所帮助。

更新 - 忽略上述

忽略了这一切,我想我知道是什么问题。看起来您正在从python-oauth2软件包中获取您的示例。他们给出的例子不使用Python的标准库imaplib,而是使用它自己的实现。

您需要使用Python-的oauth2 IMAP客户端:

import oauth2.clients.imap as imaplib 

下面是从thier例如相关的部分 - 这的确需要3个参数作为你的例子:

# This is the only thing in the API for impaplib.IMAP4_SSL that has 
# changed. You now authenticate with the URL, consumer, and token. 
conn.authenticate(url, consumer, token)