diff options
author | Fred Drake <fdrake@acm.org> | 2002-10-01 14:17:10 (GMT) |
---|---|---|
committer | Fred Drake <fdrake@acm.org> | 2002-10-01 14:17:10 (GMT) |
commit | fcc31b44d24e8e8bddc19b27c916a051223e5164 (patch) | |
tree | 2ceccfbe3d8dc6f73f94cb919d7c6c8fd1398c45 /Doc/lib/email-unpack.py | |
parent | ea66abc6e2b5d9e88f7c91aee5cea6d331b0a288 (diff) | |
download | cpython-fcc31b44d24e8e8bddc19b27c916a051223e5164.zip cpython-fcc31b44d24e8e8bddc19b27c916a051223e5164.tar.gz cpython-fcc31b44d24e8e8bddc19b27c916a051223e5164.tar.bz2 |
Split the long email package examples into separate files and use
\verbatiminput instead of the verbatim environment -- this does the "right
thing" regarding page breaks in long examples for the typeset formats, and
has nice benefits for the HTML version as well.
Diffstat (limited to 'Doc/lib/email-unpack.py')
-rw-r--r-- | Doc/lib/email-unpack.py | 83 |
1 files changed, 83 insertions, 0 deletions
diff --git a/Doc/lib/email-unpack.py b/Doc/lib/email-unpack.py new file mode 100644 index 0000000..b166fdb --- /dev/null +++ b/Doc/lib/email-unpack.py @@ -0,0 +1,83 @@ +#!/usr/bin/env python + +"""Unpack a MIME message into a directory of files. + +Usage: unpackmail [options] msgfile + +Options: + -h / --help + Print this message and exit. + + -d directory + --directory=directory + Unpack the MIME message into the named directory, which will be + created if it doesn't already exist. + +msgfile is the path to the file containing the MIME message. +""" + +import sys +import os +import getopt +import errno +import mimetypes +import email + + +def usage(code, msg=''): + print >> sys.stderr, __doc__ + if msg: + print >> sys.stderr, msg + sys.exit(code) + + +def main(): + try: + opts, args = getopt.getopt(sys.argv[1:], 'hd:', ['help', 'directory=']) + except getopt.error, msg: + usage(1, msg) + + dir = os.curdir + for opt, arg in opts: + if opt in ('-h', '--help'): + usage(0) + elif opt in ('-d', '--directory'): + dir = arg + + try: + msgfile = args[0] + except IndexError: + usage(1) + + try: + os.mkdir(dir) + except OSError, e: + # Ignore directory exists error + if e.errno <> errno.EEXIST: raise + + fp = open(msgfile) + msg = email.message_from_file(fp) + fp.close() + + 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: + ext = mimetypes.guess_extension(part.get_type()) + if not ext: + # Use a generic bag-of-bits extension + ext = '.bin' + filename = 'part-%03d%s' % (counter, ext) + counter += 1 + fp = open(os.path.join(dir, filename), 'wb') + fp.write(part.get_payload(decode=1)) + fp.close() + + +if __name__ == '__main__': + main() |