Search code examples
pythonexceptionimaplib

python: How do I catch imaplib.abort?


Here is the relevant part of my program:

    import imaplib
    ...
    try:
        M.expunge()
        M.close()
        M.logout()
    except imaplib.abort as e:
        print("IMAP abort")

And here is the error message:

Traceback (most recent call last):
 File "/home/xxx/anaconda3/lib/python3.6/imaplib.py", line 1014, in _command_complete
   typ, data = self._get_tagged_response(tag)
 File "/home/xxx/anaconda3/lib/python3.6/imaplib.py", line 1126, in _get_tagged_response
   self._check_bye()
 File "/home/xxx/anaconda3/lib/python3.6/imaplib.py", line 929, in _check_bye
   raise self.abort(bye[-1].decode(self._encoding, 'replace'))
imaplib.abort: IMAP session state is inconsistent, please relogin.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
 File "mailstats/autoresponder.py", line 224, in <module>
   M.close()
 File "/home/xxx/anaconda3/lib/python3.6/imaplib.py", line 456, in close
   typ, dat = self._simple_command('CLOSE')
 File "/home/xxx/anaconda3/lib/python3.6/imaplib.py", line 1191, in _simple_command
   return self._command_complete(name, self._command(name, *args))
 File "/home/xxx/anaconda3/lib/python3.6/imaplib.py", line 1016, in _command_complete
   raise self.abort('command: %s => %s' % (name, val))
imaplib.abort: command: CLOSE => IMAP session state is inconsistent, please relogin.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
 File "mailstats/autoresponder.py", line 226, in <module>
   except imaplib.abort as e:
AttributeError: module 'imaplib' has no attribute 'abort'

So if imaplib has no attribute called abort, then how is self.abort() being raised in line 929 of _check_bye ?

How do I catch it?


Solution

  • The "imaplib.abort" line in misleading. Actually, you need to catch imaplib.IMAP4.abort.