2002-10-01 11:17:10 -03:00
|
|
|
#!/usr/bin/env python
|
|
|
|
|
2006-03-18 11:41:53 -04:00
|
|
|
"""Unpack a MIME message into a directory of files."""
|
2002-10-01 11:17:10 -03:00
|
|
|
|
|
|
|
import os
|
2006-03-18 11:41:53 -04:00
|
|
|
import sys
|
|
|
|
import email
|
2002-10-01 11:17:10 -03:00
|
|
|
import errno
|
|
|
|
import mimetypes
|
|
|
|
|
2006-03-18 11:41:53 -04:00
|
|
|
from optparse import OptionParser
|
2002-10-01 11:17:10 -03:00
|
|
|
|
|
|
|
|
|
|
|
def main():
|
2006-03-18 11:41:53 -04:00
|
|
|
parser = OptionParser(usage="""\
|
|
|
|
Unpack a MIME message into a directory of files.
|
|
|
|
|
|
|
|
Usage: %prog [options] msgfile
|
|
|
|
""")
|
|
|
|
parser.add_option('-d', '--directory',
|
|
|
|
type='string', action='store',
|
|
|
|
help="""Unpack the MIME message into the named
|
|
|
|
directory, which will be created if it doesn't already
|
|
|
|
exist.""")
|
|
|
|
opts, args = parser.parse_args()
|
|
|
|
if not opts.directory:
|
|
|
|
parser.print_help()
|
|
|
|
sys.exit(1)
|
2002-10-01 11:17:10 -03:00
|
|
|
|
|
|
|
try:
|
|
|
|
msgfile = args[0]
|
|
|
|
except IndexError:
|
2006-03-18 11:41:53 -04:00
|
|
|
parser.print_help()
|
|
|
|
sys.exit(1)
|
2002-10-01 11:17:10 -03:00
|
|
|
|
|
|
|
try:
|
2006-03-18 11:41:53 -04:00
|
|
|
os.mkdir(opts.directory)
|
2002-10-01 11:17:10 -03:00
|
|
|
except OSError, e:
|
|
|
|
# Ignore directory exists error
|
2006-03-18 11:41:53 -04:00
|
|
|
if e.errno <> errno.EEXIST:
|
|
|
|
raise
|
2002-10-01 11:17:10 -03:00
|
|
|
|
|
|
|
fp = open(msgfile)
|
|
|
|
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:
|
2007-10-13 10:19:45 -03:00
|
|
|
ext = mimetypes.guess_extension(part.get_content_type())
|
2002-10-01 11:17:10 -03:00
|
|
|
if not ext:
|
|
|
|
# Use a generic bag-of-bits extension
|
|
|
|
ext = '.bin'
|
|
|
|
filename = 'part-%03d%s' % (counter, ext)
|
|
|
|
counter += 1
|
2006-03-18 11:41:53 -04:00
|
|
|
fp = open(os.path.join(opts.directory, filename), 'wb')
|
|
|
|
fp.write(part.get_payload(decode=True))
|
2002-10-01 11:17:10 -03:00
|
|
|
fp.close()
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
main()
|