[Pymilter] Obtaining email attachments for external processing

Stuart D. Gathman stuart at bmsi.com
Thu Sep 29 11:27:57 EDT 2011


On Thu, 29 Sep 2011, Jim Chrisos wrote:

> I am new to pymilter and despite writing many python scripts, I cannot, for
> the life of me, figure out how to obtain email attachments.
> 
> I've added a "data" function in the sample.py script since 'data' is one of
> the sendmail milter callbacks and in test emails I am able to get into that
> function.  But as far as extracting attachments for parsing with other tools
> of mine, I'm at a loss.  I've tried examples from other sample scripts such
> as check_attachments and message_from_file from the mime package but I still
> can't figure it out.  I was thinking I should be able to get the
> attachment(s) in relatively few lines of code which I could then hand off to
> my other tools, but am I mistaken?  Can anyone provide any samples to help
> me out?

You can get the attachments in relatively few lines of code.  The standard
python email module parses MIME attachments.

The milter package (my production milter that uses pymilter and is also
on sourceforge) is probably too big, but it does extensive attachment
processing.  Let me summarize:

o In the header callback, you get the header fields.  Append those to a file
or stringio.

o In the data callback, you get the body in chunks.  Append those chunks to
a file or stringio.  (Or append to a list, and join in eom.)

o Now, join the header and body with a blank line between, and you have
the email message, ready to pass to the python email module for extracting
attachments, etc.

If you will be dealing with malicious mail (spam), the email module
is not as robust as it could be when presented with malformed MIME
attachments.  The mime module provided with pymilter has patches for
some of those bugs that make it robust enough for my purposes.

If the above isn't enough, I can cobble some (untested) code as a more
explicit example.

--
 	      Stuart D. Gathman <stuart at bmsi.com>
     Business Management Systems Inc.  Phone: 703 591-0911 Fax: 703 591-6154
"Confutatis maledictis, flammis acribus addictis" - background song for
a Microsoft sponsored "Where do you want to go from here?" commercial.



More information about the Pymilter mailing list