How to fix Python IMAP 'command CLOSE illegal in state AUTH, only allowed in states SELECTED
Problem:
You have IMAP code in Python similar to
imap-example.py
server = imaplib.IMAP4_SSL('imap.mydomain.com')
server.login('[email protected]', 'password')
# ...
# Cleanup
server.close()but when you run it, server.close() fails with an error message like
imap-traceback.txt
Traceback (most recent call last):
File "./imaptest.py", line 13, in <module>
server.close()
File "/usr/lib/python3.6/imaplib.py", line 461, in close
typ, dat = self._simple_command('CLOSE')
File "/usr/lib/python3.6/imaplib.py", line 1196, in _simple_command
return self._command_complete(name, self._command(name, *args))
File "/usr/lib/python3.6/imaplib.py", line 944, in _command
', '.join(Commands[name])))
imaplib.error: command CLOSE illegal in state AUTH, only allowed in states SELECTEDSolution
Prior to server.close(), you must run server.select() at least once. If in doubt, just server.select("INBOX")because this will always work.
Insert this line before server.close():
imap-select-fix.py
server.select("INBOX")It should look like this:
imap-fixed-example.py
server = imaplib.IMAP4_SSL('imap.mydomain.com')
server.login('[email protected]', 'password')
# ...
# Cleanup
server.select("INBOX")
server.close()For a complete example see Minimal Python IMAP over SSL example
Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow