8

正如下面的错误消息所述,我无法登录,因为我处于 LOGOUT 状态而不是 NONAUTH 状态。我如何从 LOGOUT 转到 NOAUTH?

下面的示例(显然登录凭据在下面是伪造的)

Python 2.7.3 (default, Aug  1 2012, 05:14:39)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import imaplib
>>> imap_server = imaplib.IMAP4_SSL("imap.gmail.com",993)
>>> imap_server.login('something@myserver.com', 'mypassword')
('OK', ['something@myserver.com Joe Smith authenticated (Success)'])
>>> imap_server.logout()
('BYE', ['LOGOUT Requested'])
>>> imap_server.login('something@myserver.com', 'mypassword')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/imaplib.py", line 505, in login
    typ, dat = self._simple_command('LOGIN', user, self._quote(password))
  File "/usr/lib/python2.7/imaplib.py", line 1070, in _simple_command
    return self._command_complete(name, self._command(name, *args))
  File "/usr/lib/python2.7/imaplib.py", line 825, in _command
    ', '.join(Commands[name])))
imaplib.error: command LOGIN illegal in state LOGOUT, only allowed in states NONAUTH
>>> quit()
4

1 回答 1

10

您尝试做的事情在 IMAP 中是非法的。如果您阅读RFC 3501,它明确将注销状态定义为没有返回的状态。无论您是从自身收到错误imaplib,还是从服务器收到错误,或者您真的很不走运,它都会起作用并将您带入未定义的行为领域……答案都是一样的:不要这样做。

因此,您必须创建与服务器的新连接才能再次登录:

>>> imap_server.logout()
('BYE', ['LOGOUT Requested'])
>>> imap_server = imaplib.IMAP4_SSL("imap.gmail.com",993)
>>> imap_server.login('something@myserver.com', 'mypassword')
('OK', ['something@myserver.com Joe Smith authenticated (Success)'])

(当然,您不必将相同的名称重新绑定imap_server到新连接。)

于 2013-04-19T20:09:15.183 回答