"""Unpack a MIME message into a directory of files.
Usage: unpackmail [options] msgfile
Print this message and exit.
Unpack the MIME message into the named directory, which will be
created if it doesn't already exist.
msgfile is the path to the file containing the MIME message.
print >> sys
.stderr
, __doc__
opts
, args
= getopt
.getopt(sys
.argv
[1:], 'hd:', ['help', 'directory='])
except getopt
.error
, msg
:
if opt
in ('-h', '--help'):
elif opt
in ('-d', '--directory'):
# Ignore directory exists error
if e
.errno
<> errno
.EEXIST
: raise
msg
= email
.message_from_file(fp
)
# multipart/* are just containers
if part
.get_content_maintype() == 'multipart':
# Applications should really sanitize the given filename so that an
# email message can't be used to overwrite important files
filename
= part
.get_filename()
ext
= mimetypes
.guess_extension(part
.get_type())
# Use a generic bag-of-bits extension
filename
= 'part-%03d%s' % (counter
, ext
)
fp
= open(os
.path
.join(dir, filename
), 'wb')
fp
.write(part
.get_payload(decode
=1))
if __name__
== '__main__':