Calling all code critics

Sammy sammynash at uboot.com
Fri May 16 13:02:42 EDT 2003


Hi, all I'm a python beginner, and my first real project I have writen
a bit of code that is run by procmail on incomming mime emails to
extract attachments and body text as files.

Problem is it never extracts the message body, and it fails on
malformed emails.
I was wondering if you python wizzards out there could suggest some
ways for me to fix my problems and make my code more robust ie handle
dodge formatted email.

Thanks for your help,

Sam




import mimetools
import multifile
import StringIO
import sys
import rfc822

stream = sys.stdin

rfmsg = rfc822.Message(sys.stdin)
msg = mimetools.Message(stream)
msgtype = msg.gettype()
params = msg.getplist()

data = StringIO.StringIO()

if msgtype[:10] == "multipart/":

    file = multifile.MultiFile(stream)
    file.push(msg.getparam("boundary"))
    partno = 0
    while file.next():
        submsg = mimetools.Message(file)
        try:
            data = StringIO.StringIO()
            mimetools.decode(file, data, submsg.getencoding())
        except ValueError:
            bodytext = submsg
            continue

        
        partno = partno + 1
        name = submsg.getparam("name")
        if not name:
            name = "part-%i" % partno
        
        #save 
        f=open(name,"wb")
        f.write(data.getvalue())
        f.close()
        print name, "extracted to file"
    

    file.pop()

#Else if Content-Type is text/plain, get the bodytext

elif msgtype[:10] == "text/plain":
        mess = msg.fp.read()
        f=open(message.txt,"wb")
        f.write(mess)
        f.close()
        print name, "extracted to file"
    
else:
    bodytext = 'no body text'




More information about the Python-list mailing list