pythonemailmbox

python mbox unlock not working


I am using this script to remove messages from an inbox.

if(not debug):
  logging.debug("removing messages")
  all_mail.lock()
  for message in all_mail:
    all_mail.remove(message)
  all_mail.flush()
  all_mail.unlock()
all_mail.close()

After running this script once, I notice that there is still a lock file in /var/spool/mail. If I try running the script again, I get a fairly predictable exception: mailbox.ExternalClashError: dot lock unavailable

So it seems like all_mail.unlock() is not working, but I'm not really sure what more to do.


Solution

  • You script should raise an exception at all_mail.remove(message) and because of it never reaches the unlock call. A mbox as important differences from a normal dict, and here is your problem:

    The default Mailbox iterator iterates over message representations, not keys as the default dictionary iterator does.

    That means that for message in all_mail: makes msg contains a mboxMessage instead of a key and the remove raises a KeyError exception.

    Fix is simple:

    for message in all_mail.iterkeys():
        all_mail.remove(message)