faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

2 of 3 people (67%) answered Yes
Recently 0 of 1 people (0%) answered Yes

Entry

Unmimify

Jul 5th, 2000 10:03
Nathan Wallace, Hans Nowak, Snippet 296, Fredrik Lundh


"""
Packages: networking.mail
"""
"""
> Does anyone know if a module exists that would take an email message
> with or without attachments and create objects for each portion of the
> message?
not really, but the multifile and mimetools/rfc822
modules (all in the standard library) will take you
a bit closer to a solution.  here's something to
start with:
"""
#
# multifile-example-1.py (from the eff-bot guide)
import multifile
import cgi, rfc822
infile = open("samples/sample.msg")
# PSST: Replace this with a valid message file
message = rfc822.Message(infile)
# print parsed header
for k, v in message.items():
    print k, "=", v
# use cgi support function to parse content-type header
type, params = cgi.parse_header(message["content-type"])
if type[:10] == "multipart/":
    # multipart message
    boundary = params["boundary"]
    file = multifile.MultiFile(infile)
    file.push(boundary)
    while file.next():
        submessage = rfc822.Message(file)
        # print submessage
        print "-" * 68
        for k, v in submessage.items():
            print k, "=", v
        print
        print file.read()
    file.pop()
else:
    # plain message
    print infile.read()
"""
this code merely prints the subpart bodies; use uu,
base64, or quopri to decode them (you may wish to
change rfc822 to mimetools in the above example,
to make it a bit easier to deal with the content-type
header field).
"""