3 """Unpack a MIME message into a directory of files."""
11 from optparse
import OptionParser
15 parser
= OptionParser(usage
="""\
16 Unpack a MIME message into a directory of files.
18 Usage: %prog [options] msgfile
20 parser
.add_option('-d', '--directory',
21 type='string', action
='store',
22 help="""Unpack the MIME message into the named
23 directory, which will be created if it doesn't already
25 opts
, args
= parser
.parse_args()
26 if not opts
.directory
:
37 os
.mkdir(opts
.directory
)
39 # Ignore directory exists error
40 if e
.errno
<> errno
.EEXIST
:
44 msg
= email
.message_from_file(fp
)
48 for part
in msg
.walk():
49 # multipart/* are just containers
50 if part
.get_content_maintype() == 'multipart':
52 # Applications should really sanitize the given filename so that an
53 # email message can't be used to overwrite important files
54 filename
= part
.get_filename()
56 ext
= mimetypes
.guess_extension(part
.get_type())
58 # Use a generic bag-of-bits extension
60 filename
= 'part-%03d%s' % (counter
, ext
)
62 fp
= open(os
.path
.join(opts
.directory
, filename
), 'wb')
63 fp
.write(part
.get_payload(decode
=True))
67 if __name__
== '__main__':