How to fix Python IMAP 'command CLOSE illegal in state AUTH, only allowed in states SELECTED

English Deutsch

Problem:

Du hast IMAP-Code in Python ähnlich wie

imap-example.py
server = imaplib.IMAP4_SSL('imap.mydomain.com')
server.login('email@mydomain.com', 'password')
# ...
# Cleanup
server.close()

aber wenn du ihn ausführst, schlägt server.close() mit einer Fehlermeldung wie

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 SELECTED

Lösung

Vor server.close() musst du mindestens einmal server.select() ausführen. Im Zweifel einfach server.select("INBOX"), da dies immer funktionieren wird.

Füge diese Zeile vor server.close() ein:

imap-select-fix.py
server.select("INBOX")

Es sollte so aussehen:

imap-fixed-example.py
server = imaplib.IMAP4_SSL('imap.mydomain.com')
server.login('email@mydomain.com', 'password')
# ...
# Cleanup
server.select("INBOX")
server.close()

Für ein vollständiges Beispiel siehe Minimal Python IMAP over SSL example


Check out similar posts by category: Python