ยปCore Development>Code coverage>Doc/includes/email-unpack.py

Python code coverage for Doc/includes/email-unpack.py

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