Gmail IMAP认证 -- imaplib.authenticate需要3个参数(给了4个)

1 投票
2 回答
3514 浏览
提问于 2025-04-17 05:24

我正在尝试从我的网页应用程序启用Gmail的IMAP访问。目前,用户可以授权这个网页应用程序,并成功获取和存储用户的令牌和密钥。但是,当我尝试进行IMAP连接以获取电子邮件时,出现了以下错误:

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/username@gmail.com/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 个回答

1

这个authenticate方法只需要两个参数(加上self就是三个)。这篇文章解释了它是怎么工作的(官方文档不是很有帮助)。

你的第二次尝试看起来不错,只要提供这两个参数就行:

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

这是他们例子中的相关部分 - 确实需要三个参数,就像你例子里那样:

# 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)
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

撰写回答