Howto use email module and write the get_payload to a file
Piet van Oostrum
piet at cs.uu.nl
Tue Jun 22 21:05:51 EDT 2004
>>>>> chuck amadi <chuck.amadi at ntlworld.com> (CA) wrote:
CA> Hi I have managed to print the output of the get_payload to screen
CA> but I need to write to a file as I only require the email body messages
CA> from the mailbox.My script using the fp.readlines() function writes the
CA> entire contents of the mailbox of cause including the headers of the
CA> emails I do not want.
CA> mailout = file("/home/chucka/pythonScript/SurveyResults1.txt","r")
If you open the file with "r" you can't write to it.
CA> fp = open("/var/spool/mail/chucka")
CA> mb = mailbox.UnixMailbox(fp, email.message_from_file)
CA> for bmsg in mb:
CA> bmsg = get_payload()
You use bmsg for two purposes: as the iteration variable, and to get the
payload. Moreover get_payload is a method and hence needs an object.
for bmsg in mb:
msgb = bmsg.get_payload()
mailout.write(msgb)
But that doesn't take into account that the payload will be a list when
the message is multipart. In that case you need some more elaborate code
like:
def writebody(mailout, msg):
payld = msg.get_payload()
if msg.is_multipart():
for m in payld:
writebody(mailout, m)
else:
mailout.write(payld)
for bmsg in mb:
writebody(mailout, bmsg)
print "mailbox file copied...to SurveyResults.txt"
--
Piet van Oostrum <piet at cs.uu.nl>
URL: http://www.cs.uu.nl/~piet [PGP]
Private email: P.van.Oostrum at hccnet.nl
More information about the Python-list
mailing list