#!/usr/bin/env python # # Takes an email message string on standard input and saves attachments to the # current directory. A full or partial attachment mime type can be specified # as an argument e.g. 'text/calendar' or 'image'. import sys, email, re attachment_type = len(sys.argv[1:]) and '^' + sys.argv[1] for part in email.message_from_string(sys.stdin.read()).walk(): if part.get_filename() and ((not attachment_type) or re.search(attachment_type, part.get_content_type())): print "-> Saving '%s'" % part.get_filename() f = open(part.get_filename(), "w") f.write(part.get_payload(decode=True)) f.close