How to get key values when iterating a mailbox?

Chris Rebert clp2 at
Mon Oct 18 18:57:19 CEST 2010

On Mon, Oct 18, 2010 at 8:42 AM,  <tinnews at> wrote:
> I'm trying to delete some messages from a mailbox when they are older
> than a certain number of days.
> If I iterate through the mailbox and find a message that needs
> deleting how do I get its key so I can do "remove(key)"?
> The trouble is that, as the documentation says: "The default Mailbox
> iterator iterates over message representations, not keys as the
> default dictionary iterator does." So if you try something like:-
>    for f in os.listdir(junkdir):
>        mbxPath = os.path.join(junkdir, f)
>        mbx = mailbox.mbox(mbxPath, factory=None)
>        mbx.lock()
>        for k, msg in mbx:
>            if <something is true>
>                msg.remove(k)
>        mbx.flush()
>        mbx.unlock()
> Then you get an exception on "for k, msg in mbx" which is an attribute
> error, presumably because a mailbox isn't a 'real' iterator.

No, it's probably because iterating over a Mailbox yields Message-s
rather than (key, Message) pairs; Python thus tries to unpack each
Message into a (k, msg) pair (since that's how you wrote your
for-loop), but this fails since (I would assume) Messages aren't

> So how,
> do I get that key value?

If you want to iterate over key-value pairs (aka "items"), then ask
Mailbox for items in the first place:

for k, msg in mbx.iteritems():
    # rest of code


More information about the Python-list mailing list