blob: e0a7f01f58bb59078e58b00112eda388117b8294 [file] [log] [blame]
Benjamin Peterson90f5ba52010-03-11 22:53:45 +00001#!/usr/bin/env python3
Georg Brandl116aa622007-08-15 14:28:22 +00002
3"""Unpack a MIME message into a directory of files."""
4
5import os
Georg Brandl116aa622007-08-15 14:28:22 +00006import email
Georg Brandl116aa622007-08-15 14:28:22 +00007import mimetypes
8
R David Murray29d1bc02016-09-07 21:15:59 -04009from email.policy import default
10
Serhiy Storchaka992cf1d2013-10-06 11:45:25 +030011from argparse import ArgumentParser
Georg Brandl116aa622007-08-15 14:28:22 +000012
13
14def main():
Serhiy Storchaka992cf1d2013-10-06 11:45:25 +030015 parser = ArgumentParser(description="""\
Georg Brandl116aa622007-08-15 14:28:22 +000016Unpack a MIME message into a directory of files.
Georg Brandl116aa622007-08-15 14:28:22 +000017""")
Serhiy Storchaka992cf1d2013-10-06 11:45:25 +030018 parser.add_argument('-d', '--directory', required=True,
19 help="""Unpack the MIME message into the named
20 directory, which will be created if it doesn't already
21 exist.""")
22 parser.add_argument('msgfile')
23 args = parser.parse_args()
24
R David Murray29d1bc02016-09-07 21:15:59 -040025 with open(args.msgfile, 'rb') as fp:
26 msg = email.message_from_binary_file(fp, policy=default)
Georg Brandl116aa622007-08-15 14:28:22 +000027
28 try:
Serhiy Storchaka992cf1d2013-10-06 11:45:25 +030029 os.mkdir(args.directory)
30 except FileExistsError:
31 pass
Georg Brandl116aa622007-08-15 14:28:22 +000032
33 counter = 1
34 for part in msg.walk():
35 # multipart/* are just containers
36 if part.get_content_maintype() == 'multipart':
37 continue
38 # Applications should really sanitize the given filename so that an
39 # email message can't be used to overwrite important files
40 filename = part.get_filename()
41 if not filename:
Georg Brandl9afde1c2007-11-01 20:32:30 +000042 ext = mimetypes.guess_extension(part.get_content_type())
Georg Brandl116aa622007-08-15 14:28:22 +000043 if not ext:
44 # Use a generic bag-of-bits extension
45 ext = '.bin'
46 filename = 'part-%03d%s' % (counter, ext)
47 counter += 1
Serhiy Storchaka992cf1d2013-10-06 11:45:25 +030048 with open(os.path.join(args.directory, filename), 'wb') as fp:
49 fp.write(part.get_payload(decode=True))
Georg Brandl116aa622007-08-15 14:28:22 +000050
51
52if __name__ == '__main__':
53 main()