如何使用Python从msg文件中提取附件?
import os
import sys
import email
import errno
import mimetypes
from optparse import OptionParser
if __name__ == "__main__":
fp = open("C:/FNFData/emails/e_1512_1_message.msg")
msg = email.message_from_file(fp)
fp.close()
counter = 1
print msg['From']
print msg['Subject']
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()
#print filename
if not filename:
ext = mimetypes.guess_extension(part.get_content_type())
print "Extension :", ext
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("C:\\FNFData\\emails", filename), 'wb')
fp.write(part.get_payload(decode=True))
fp.close()
print counter
此代码不起作用,并将“ksh”标识为附件的扩展名而不是pdf。它还显示“To”,“From”,“Subject”等所有内容为NONE ... 有什么想法吗?
由于
Parag