Simple Python script to read and output MailBox body to a file

chuck amadi chuck.amadi at ntlworld.com
Sun Jun 6 17:54:06 CEST 2004


Eric S. Johansson wrote:

> William Park wrote:
>
>> Chuck Amadi <chuck at smtl.co.uk> wrote:
>>
>>> Has anyone got a simple python script that will parse a linux  mbox
>>> and create a large file to view .
>>
>>
>>
>> "Create a large file to view"?  Care to elaborate?
>
>
> I've sent him a working example that disassembles mailboxes in both 
> mbox and maildir form.  Personally, I'm now scouting around for code 
> that will let you delete and expunge messages from an mbox mailbox.  I 
> fear I need to pull my thumb out and expand the mailbox module to 
> handle writing as well.  mbox manipulations are butt ugly.
>
> ---eric
>
> Cheers I do note that I need to create a global-config file I have 
> seen something on this in O'Reilly Python Programming . Albiet I dont 
> need to connect to a pop3 account .Thus would this script need a bit 
> of hacking or is the script I got sufficient as Monday 7th is my D-Day 
> to get that script working and demo to my boss.

Note briefly my main goal is to get the body content to another file for 
processing to Postgresql database.

#file: getSurveyMail.py
## The email messages is read as flat text form a file or other source,
##the text is parsed to produce the object structure of the email message.
#!/usr/bin/env python

import mboxutils
import mailbox
import email
import sys
import os
import rfc822
import StringIO
import email.Parser
import types
 
# email package for managing email messages
# Open Users Mailbox
# class Message()
 
def main():
 
# The Directory that will contain the Survey Results
 
    dir = "/tmp/SurveyResults/"
# The Web Survey User Inbox
# Mailbox /home/testwwws/Mail/inbox
 
    maildir = "/home/testwwws/Mail/inbox"
    for file in os.listdir(maildir):
 
        print os.path.join(maildir, file)
 
        fp = open(os.path.join(maildir, file), "rb")
        p = email.Parser.Parser()
        msg = p.parse(fp)
        fp.close()
        #print msg.get("From")
        #print msg.get("Content-Type")
 
        counter = 1
        for part in msg.walk():
          if part.get_main_type() == 'multipart':
            continue
 
          filename = part.get_param("name")
          if filename==None:
                filename = "part-%i" % counter
          counter += 1
 
 
          fp = open(os.path.join(dir, filename), 'wb')
          print os.path.join(dir, filename)
          fp.write(part.get_payload(decode=1))
          fp.close()
 
 
if __name__ == '__main__':
    main()


>
>
>






More information about the Python-list mailing list