3 """Unpack a MIME message into a directory of files.
5 Usage: unpackmail [options] msgfile
9 Print this message and exit.
13 Unpack the MIME message into the named directory, which will be
14 created if it doesn't already exist.
16 msgfile is the path to the file containing the MIME message.
27 def usage(code
, msg
=''):
28 print >> sys
.stderr
, __doc__
30 print >> sys
.stderr
, msg
36 opts
, args
= getopt
.getopt(sys
.argv
[1:], 'hd:', ['help', 'directory='])
37 except getopt
.error
, msg
:
42 if opt
in ('-h', '--help'):
44 elif opt
in ('-d', '--directory'):
55 # Ignore directory exists error
56 if e
.errno
<> errno
.EEXIST
: raise
59 msg
= email
.message_from_file(fp
)
63 for part
in msg
.walk():
64 # multipart/* are just containers
65 if part
.get_content_maintype() == 'multipart':
67 # Applications should really sanitize the given filename so that an
68 # email message can't be used to overwrite important files
69 filename
= part
.get_filename()
71 ext
= mimetypes
.guess_extension(part
.get_type())
73 # Use a generic bag-of-bits extension
75 filename
= 'part-%03d%s' % (counter
, ext
)
77 fp
= open(os
.path
.join(dir, filename
), 'wb')
78 fp
.write(part
.get_payload(decode
=1))
82 if __name__
== '__main__':