Benjamin Peterson | 90f5ba5 | 2010-03-11 22:53:45 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2 | |
| 3 | """Unpack a MIME message into a directory of files.""" |
| 4 | |
| 5 | import os |
| 6 | import sys |
| 7 | import email |
| 8 | import errno |
| 9 | import mimetypes |
| 10 | |
Serhiy Storchaka | 992cf1d | 2013-10-06 11:45:25 +0300 | [diff] [blame] | 11 | from argparse import ArgumentParser |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 12 | |
| 13 | |
| 14 | def main(): |
Serhiy Storchaka | 992cf1d | 2013-10-06 11:45:25 +0300 | [diff] [blame] | 15 | parser = ArgumentParser(description="""\ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 16 | Unpack a MIME message into a directory of files. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 17 | """) |
Serhiy Storchaka | 992cf1d | 2013-10-06 11:45:25 +0300 | [diff] [blame] | 18 | 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 | |
| 25 | with open(args.msgfile) as fp: |
| 26 | msg = email.message_from_file(fp) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 27 | |
| 28 | try: |
Serhiy Storchaka | 992cf1d | 2013-10-06 11:45:25 +0300 | [diff] [blame] | 29 | os.mkdir(args.directory) |
| 30 | except FileExistsError: |
| 31 | pass |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 32 | |
| 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 Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 42 | ext = mimetypes.guess_extension(part.get_content_type()) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 43 | 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 Storchaka | 992cf1d | 2013-10-06 11:45:25 +0300 | [diff] [blame] | 48 | with open(os.path.join(args.directory, filename), 'wb') as fp: |
| 49 | fp.write(part.get_payload(decode=True)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 50 | |
| 51 | |
| 52 | if __name__ == '__main__': |
| 53 | main() |