Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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('[email protected]', 'mypassword')
('OK', ['[email protected] Joe Smith authenticated (Success)'])
>>> imap_server.logout()
('BYE', ['LOGOUT Requested'])
>>> imap_server.login('[email protected]', '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()
like image 963
dl__ Avatar asked Apr 19 '13 20:04

dl__


1 Answers

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('[email protected]', 'mypassword')
('OK', ['[email protected] Joe Smith authenticated (Success)'])

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

like image 84
abarnert Avatar answered Nov 14 '22 20:11

abarnert