How to iterate through maildir messages in python 3?

Greg Ewing greg.ewing at canterbury.ac.nz
Thu Jun 24 20:21:40 EDT 2021


On 25/06/21 7:06 am, Chris Green wrote:
> In python 2 one can do:-
> 
>     for msg in maildir:
>            print msg      # or whatever you want to do with the message
> 
> 
> However in python 3 this produces "TypeError: string argument
> expected, got 'bytes'".
> 
> How should one iterate over a maildir in python3?

You're already iterating over it just fine. Your problem is
actually how to *print* a mail message.

The answer to this will depend on what your purpose is. If
you just want a rough-and-ready idea of what the message
contains, you could do this:

     print(repr(msg))

However, that won't work very well if the message doesn't
consist of mostly text in an ASCII-compatible encoding.

If you want something better, Python comes with some standard
library code for dealing with mail messages. Check out the
'email' module.

-- 
Greg


More information about the Python-list mailing list