- Notifications
You must be signed in to change notification settings - Fork 31.8k
/
Copy pathemail-unpack.py
68 lines (56 loc) · 1.8 KB
/
email-unpack.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/usr/bin/env python
"""Unpack a MIME message into a directory of files."""
importos
importsys
importemail
importerrno
importmimetypes
fromoptparseimportOptionParser
defmain():
parser=OptionParser(usage="""\
Unpack a MIME message into a directory of files.
Usage: %prog [options] msgfile
""")
parser.add_option('-d', '--directory',
type='string', action='store',
help="""Unpack the MIME message into the named
directory, which will be created if it doesn't already
exist.""")
opts, args=parser.parse_args()
ifnotopts.directory:
parser.print_help()
sys.exit(1)
try:
msgfile=args[0]
exceptIndexError:
parser.print_help()
sys.exit(1)
try:
os.mkdir(opts.directory)
exceptOSErrorase:
# Ignore directory exists error
ife.errno!=errno.EEXIST:
raise
fp=open(msgfile)
msg=email.message_from_file(fp)
fp.close()
counter=1
forpartinmsg.walk():
# multipart/* are just containers
ifpart.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()
ifnotfilename:
ext=mimetypes.guess_extension(part.get_content_type())
ifnotext:
# Use a generic bag-of-bits extension
ext='.bin'
filename='part-%03d%s'% (counter, ext)
counter+=1
fp=open(os.path.join(opts.directory, filename), 'wb')
fp.write(part.get_payload(decode=True))
fp.close()
if__name__=='__main__':
main()