Why can't I login to an imap server twice in Python

こ雲淡風輕ζ 提交于 2020-01-02 04:16:46

问题


As the error message below states, I cannot log in because I'm in state LOGOUT and not in state NONAUTH. How do I get from LOGOUT to NONAUTH?

Example below (obviously the login credentials are faked below)

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

回答1:


What you're trying to do is illegal in IMAP. If you read over RFC 3501, it explicitly defines Logout State as a state from which there is no return. Whether you get an error from imaplib itself, or from the server, or you get really unlucky and it works and takes you into undefined-behavior territory… the answer is the same: don't do it.

So, you have to create a new connection to the server to login again:

>>> 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)'])

(Of course you don't have to rebind the same name imap_server to the new connection.)



来源:https://stackoverflow.com/questions/16112695/why-cant-i-login-to-an-imap-server-twice-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!