0

I am trying to write a script that gets me the contents of all the Mails in ~/Maildir. So I basically copypasted code from this question. Here is the full content of mailbox.py:

import mailbox
maildir = mailbox.Maildir("~/Maildir");
for message in maildir:
    print message["subject"]
    if message.is_multipart():
        print "ok"

It does print the subject of the first message, but instead of printing "ok" then, it dies stating

AttributeError: Message instance has no attribute 'is_multipart'

What did I do wrong?

mcnesium
  • 1,423
  • 2
  • 16
  • 21
  • could you give an example of a file in `~/MailDir`? – glS Aug 21 '17 at 19:55
  • [`is_multipart()`](https://docs.python.org/2/library/email.message.html#email.message.Message.is_multipart) is a method of [`email.message.Message`](https://docs.python.org/2/library/email.message.html#email.message.Message) so you need a `email.message.Message` object to apply it to. What's the type of `message`? – user2314737 Aug 21 '17 at 20:09
  • @user2314737: presumably this is the [`mailbox` module](https://docs.python.org/3/library/mailbox.html) in the stdlib, so [this class](https://docs.python.org/3/library/mailbox.html#mailbox.Message), a subclass of `email.message.Message`.. – Martijn Pieters Aug 21 '17 at 20:22

1 Answers1

1

You have forgotten to name your Python version so let me guess — it's Python 2.7, right? In Python 2.7 mailbox.Maildir by default returns instances of rfc822.Messages, not email.Messages; rfc822.Message has a completely different API.

If you want mailbox.Maildir to return email.Messages remove default factory:

maildir = mailbox.Maildir("~/Maildir", factory=None)

In Python 3 rfc822.Message was removed so mailbox.Maildir returns email.Messages by default.

phd
  • 82,685
  • 13
  • 120
  • 165
  • You got it. when I run it using `python3 mailbox.py` it works as expected. Thx for pointing me to it. – mcnesium Aug 22 '17 at 15:25