Getting the attachment from a mime message

Steve Holden sholden at holdenweb.com
Thu Sep 7 16:35:42 CEST 2000


Thomas Gagne wrote:
> 
> I'm not having much luck figuring out how Mime messages are disected.  Given:
> 
> m = mimetools.Message(fp)
> 
> m.items() has all the header values, but what message returns a decoded
> attachment?  How do you handle a message with multiiple attachments?  How do
> you know if you're pointing to an attachment and not just some random place in
> the message body?
> 
> --
> .tom

Tom:

Using the mimecntl library, and Tkinter, here's an extract from a program
which displays multi-part and standard messages.  This may give you some
ideas about how to do the same thing in mimetools, or it may not.  Having
tried both, I find mimecntl to be much easier to deal with, but that's
just personal choice.  The display is not elegant: this is a work-in-
progress.

In the code below, strmes is a StringIO containing the message, as a
"file-like" object is required ...

Hope this helps.

regards
 Steve

        message = mimecntl.MIME_document(strmes)
        for hdr in ("from", "date", "subject", "to", "cc"):
            try:
                hdrline = message[hdr]
                t.insert(END, "%s:     %s\n" %
(string.capitalize(hdr),hdrline))
            except KeyError:
                pass
        try:
    	    multipart = message["content-type"].majortype() == "multipart"
        except KeyError:
            multipart = 0
        if multipart:
            tflag = 0
            # t.insert(END, "Multipart message with %d items\n\n" %
            #                              (len(message),))
            for i in range(len(message)):
                part = message[i]
                if tflag == 0 and str(part["content-type"]) == "text/plain":
                    part.seek(0)
                    lct = 0
                    t.insert(END, '\n')
                    while 1:
                        line = part.readline()
                        if line == '': break
                        t.insert(END, line)
                        lct = lct+1
                    tflag = 1
                else:
                    t.insert(END, "\nPART %d: |%s|\n" % (i,
part["content-type"]))
        else:
            message.seek(0)
            lct = 0
            t.insert(END, '\n')
            while 1:
                line = message.readline()
                if line == '': break
                t.insert(END, line)
                lct = lct+1
  
-- 
Helping people meet their information needs with training and technology.
703 967 0887      sholden at bellatlantic.net      http://www.holdenweb.com/



More information about the Python-list mailing list