[Tutor] rfc822.rewindbody()
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Fri, 21 Dec 2001 12:59:32 -0800 (PST)
On Fri, 21 Dec 2001, Kirk Bailey wrote:
> OK, I confizedde... how do I properly use rewindbody()?
Let's say that we have a sample message, like this:
###
m = """From sclaus@northpole.com Tue Dec 25 15:49:13 2001 -0800
Date: Tue, 25 Dec 2001 15:49:13 -0800 (PST)
From: Santa <sclaus@northpole.net>
To: Ebenezer <moneymoney@money.com>
Here. Have a lump of coal.
"""
###
When we have something like this, rfc822.Message can parse it out into a
bunch of headers and the message body. Since we're making a message from
a string, we need to wrap it with StringIO to make it look like a file:
###
>>> msg = rfc822.Message(StringIO.StringIO(m))
###
Now that we have this parsed message, we can read it's contents! The
message body becomes accessible through an 'fp' attribute:
###
>>> msg.fp.read()
'Here. Have a lump of coal.
\012'
>>> msg.fp.read()
''
###
But notice that we can only read it once(); if we want to read it again,
we need to rewindbody() back:
###
>>> msg.rewindbody()
>>> msg.fp.read()
'Here. Have a lump of coal.
\012'
###
What's nice about rfc822.Message is that the headers are all there for us
too:
###
>>> msg.getheader('from')
'Santa <sclaus@northpole.net>'
>>> msg.getheader('to')
'Ebenezer <moneymoney@money.com>'
>>> msg.getheader('date')
'Tue, 25 Dec 2001 15:49:13 -0800 (PST)'
###
Happy holidays!