为什么我不能在Python中两次登录到imap服务器
作者:互联网
如下面的错误消息所示,我无法登录,因为我处于状态LOGOUT而不处于状态NONAUTH.如何从LOGOUT到NONAUTH?
下面的示例(显然登录凭据是伪造的)
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()
解决方法:
您在IMAP中尝试做的是非法的.如果您阅读了RFC 3501,它会明确将Logout State定义为没有返回的状态.无论你是从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重新绑定到新连接.)
标签:python,imap,imaplib 来源: https://codeday.me/bug/20190517/1122549.html