Stripping attachments out of email

So I developed the need to strip attachments out of emails … or rather, to get hold of the attachments and store them to disk.  A lot of googling later only one solution seemed to surface and seeing that I couldn’t get at metamail’s homepage and thus the packages I had to go another root.  So after posing the question in on FreeNODE python once more came up.  This time I decided to just take the plunge and write some python …

And eventually came up with this snippet of code:

#! /usr/bin/python

import email;
import sys;

msg = email.message_from_file(sys.stdin)

if msg.is_multipart():
  for part in msg.walk():
  if not part.is_multipart():
    disposition = part['Content-Disposition']
    if disposition != None and disposition[0:10].lower() == "attachment":
      content = part.get_payload(None, True)
      fp = open(part.get_filename(), "w")

It’s a simple enough piece of code. It reads an RFC compliant (hopefully) message from stdin, parses it (let’s hope there is sufficient RAM), and then I just basically walk it. It does NOT handle uuencoded attachments, but I’m not aware of any email clients that still send them, so sufficient for my purposes. Also, all files are stored in the current working directory – so make sure you invoke this script where you want the files to be stored.

TODO: Check securiry implications of things like filename=fneh/bar :).

Leave a Reply