#!/usr/bin/env python # -*- coding: utf-8 -*- import email import mimetypes import os import os.path import sys def usage (): print print "Usage:" print print sys.argv[0] + " file" print print "Extract inline attachment of mail and put them in ~/tmp" print print "Argument file is message to be parsed." sys.exit(1) if len(sys.argv) != 2: usage() fp = open (sys.argv[1]) msg = email.message_from_file(fp) fp.close() counter = 1 for part in msg.walk(): # multipart/* are just containers if part.get_content_maintype() == 'multipart': continue # Applications should really sanitize the given filename so that an # email message can't be used to overwrite important files filename = part.get_filename() if not filename: ext = mimetypes.guess_extension(part.get_content_type()) if not ext: # Use a generic bag-of-bits extension ext = '.bin' filename = 'part-%03d%s' % (counter, ext) counter += 1 filename = os.path.expanduser ("~/tmp/" + filename) print filename fp = open(filename, 'wb') fp.write(part.get_payload(decode=True)) fp.close() # Copyright (C) 2012 Ivan Kanis # Author: Ivan Kanis # # This program is free software ; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation ; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY ; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program ; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # vi:et:sw=4:ts=4: # Local Variables: # compile-command: "python foo.py" # End: # # vi:et:sw=4:ts=4: