1 | n/a | #!/usr/bin/env python3 |
---|
2 | n/a | |
---|
3 | n/a | """Unpack a MIME message into a directory of files.""" |
---|
4 | n/a | |
---|
5 | n/a | import os |
---|
6 | n/a | import email |
---|
7 | n/a | import mimetypes |
---|
8 | n/a | |
---|
9 | n/a | from email.policy import default |
---|
10 | n/a | |
---|
11 | n/a | from argparse import ArgumentParser |
---|
12 | n/a | |
---|
13 | n/a | |
---|
14 | n/a | def main(): |
---|
15 | n/a | parser = ArgumentParser(description="""\ |
---|
16 | n/a | Unpack a MIME message into a directory of files. |
---|
17 | n/a | """) |
---|
18 | n/a | parser.add_argument('-d', '--directory', required=True, |
---|
19 | n/a | help="""Unpack the MIME message into the named |
---|
20 | n/a | directory, which will be created if it doesn't already |
---|
21 | n/a | exist.""") |
---|
22 | n/a | parser.add_argument('msgfile') |
---|
23 | n/a | args = parser.parse_args() |
---|
24 | n/a | |
---|
25 | n/a | with open(args.msgfile, 'rb') as fp: |
---|
26 | n/a | msg = email.message_from_binary_file(fp, policy=default) |
---|
27 | n/a | |
---|
28 | n/a | try: |
---|
29 | n/a | os.mkdir(args.directory) |
---|
30 | n/a | except FileExistsError: |
---|
31 | n/a | pass |
---|
32 | n/a | |
---|
33 | n/a | counter = 1 |
---|
34 | n/a | for part in msg.walk(): |
---|
35 | n/a | # multipart/* are just containers |
---|
36 | n/a | if part.get_content_maintype() == 'multipart': |
---|
37 | n/a | continue |
---|
38 | n/a | # Applications should really sanitize the given filename so that an |
---|
39 | n/a | # email message can't be used to overwrite important files |
---|
40 | n/a | filename = part.get_filename() |
---|
41 | n/a | if not filename: |
---|
42 | n/a | ext = mimetypes.guess_extension(part.get_content_type()) |
---|
43 | n/a | if not ext: |
---|
44 | n/a | # Use a generic bag-of-bits extension |
---|
45 | n/a | ext = '.bin' |
---|
46 | n/a | filename = 'part-%03d%s' % (counter, ext) |
---|
47 | n/a | counter += 1 |
---|
48 | n/a | with open(os.path.join(args.directory, filename), 'wb') as fp: |
---|
49 | n/a | fp.write(part.get_payload(decode=True)) |
---|
50 | n/a | |
---|
51 | n/a | |
---|
52 | n/a | if __name__ == '__main__': |
---|
53 | n/a | main() |
---|