Question about email-handling modules
Matt Nordhoff
mnordhoff at mattnordhoff.com
Thu Dec 20 05:59:48 EST 2007
Robert Latest wrote:
> Hello,
>
> I'm new to Python but have lots of programming experience in C, C++ and
> Perl. Browsing through the docs, the email handling modules caught my eye
> because I'd always wanted to write a script to handle my huge, ancient, and
> partially corrupted email archives.
>
> Of course I know that this kind of project shouldn't be tackled by a
> beginner in a language, but I still thought I'd give it a spin.
>
> So I wrote the stuff at the bottom. It lists senders, subjects and
> addressees of all messages in an mbox.
>
> Things that I don't understand:
>
> 1. Why can I get the 'subject' and 'from' header field unsig the []
> notation, but not 'to'? When I print Message.keys I get a list of all header
> fields of the message, including 'to'. What's the difference between
> message['to'] and message.get('to')?
On dicts, and presumably on Messages too, .get returns a default value
(None, or you can specify another with .get("key", "default") if the key
doesn't exist.
I can't say why ['to'] doesn't work when it's in the list of keys, though.
> 2. Why can't I call the get_payload() method on the message? What I get is
> this cryptic error: "AttributeError: Message instance has no attribute
> 'get_payload'". I'm trying to call a method here, not an attribute. It makes
> no difference if I put parentheses after get_payload or not. I looked into
> the email/Message module and found get_payload defined there.
Methods are attributes. When you do "obj.method()", "obj.method" and
"()" are really two separate things: It gets the "method" attribute of
"obj", and then calls it.
> I don't want to waste your time by requesting that you pick apart my silly
> example. But maybe you can give me a pointer in the right direction. This is
> python 2.4 on a Debian box.
>
> ---------------------------
>
> #!/usr/bin/python
> import mailbox
> import email # doesn't make a difference
> from email import Message # neither does this
>
> mbox = file("mail.old/friends")
>
> for message in mailbox.UnixMailbox(mbox):
> subject = message['subject']
> frm = message['from']
> # to = message['to'] # this throws a "Key Error"
> to = message.get('to'); # ...but this works
> print frm, "writes about", subject, "to", to
> # print message.get_payload() # this doesn't work
>
> --------------------------
>
> robert
(Oops, I wrote this like half an hour ago, but I never sent it.)
--
More information about the Python-list
mailing list