email-unpack.py 1.51 KB
Newer Older
1
#!/usr/bin/env python3
2 3 4 5 6 7 8 9 10

"""Unpack a MIME message into a directory of files."""

import os
import sys
import email
import errno
import mimetypes

11
from argparse import ArgumentParser
12 13 14


def main():
15
    parser = ArgumentParser(description="""\
16 17
Unpack a MIME message into a directory of files.
""")
18 19 20 21 22 23
    parser.add_argument('-d', '--directory', required=True,
                        help="""Unpack the MIME message into the named
                        directory, which will be created if it doesn't already
                        exist.""")
    parser.add_argument('msgfile')
    args = parser.parse_args()
24

25 26
    with open(args.msgfile) as fp:
        msg = email.message_from_file(fp)
27 28

    try:
29 30 31
        os.mkdir(args.directory)
    except FileExistsError:
        pass
32 33 34 35 36 37 38 39 40 41

    counter = 1
    for part in msg.walk():
        # multipart/* are just containers
        if part.get_content_maintype() == 'multipart':
            continue
        # Applications should really sanitize the given filename so that an
        # email message can't be used to overwrite important files
        filename = part.get_filename()
        if not filename:
42
            ext = mimetypes.guess_extension(part.get_content_type())
43 44 45 46 47
            if not ext:
                # Use a generic bag-of-bits extension
                ext = '.bin'
            filename = 'part-%03d%s' % (counter, ext)
        counter += 1
48 49
        with open(os.path.join(args.directory, filename), 'wb') as fp:
            fp.write(part.get_payload(decode=True))
50 51 52 53


if __name__ == '__main__':
    main()