python获取outlook导出eml文件中附件代码
background:离职,公司邮箱是一直从浏览器来访问的,所以邮件在本地保存不了。如果没有附件的话可以直接用word打开。但是有附件就会打开出错。
同时导出也只能是eml格式
其实里边就是文本信息,邮件发送也是这些文本。
所以就很简单了
复用了以前 的代码
#!/usr/bin/env python
#encoding=utf-8
"""
Copyright (c) 2012 ekse <5thgfka@gmail.com>
All rights reserved.
"""
import email, os
from optparse import OptionParser
class work:
# class to get attachement
def __init__(self, directory = './'):
self.directory = directory
self.body = ''
def getAtt(self):
# traverse the directory
for root, dirs, files in os.walk(self.directory):
for fl in files:
routine = self.directory + r'\\' + fl
print routine
filepointer = open(routine, 'r')
# read file as email
for line in filepointer:
self.body += line
mail = email.message_from_string(self.body)
# walk the stream, get attachement
for part in mail.walk():
filename = email.Header.decode_header\
(part.get_filename())
att_path = os.path.join(self.directory, filename)
outfile = open(att_path, 'wb')
if part.get_payload(decode = True):
outfile.write(part.get_payload(decode = True))
outfile.close()
def main():
# use OptionParser to privide opt
usage = "usage: %prog arg"
parser = OptionParser(usage)
parser.add_option("-d", "--dir", dest="directory",
help="processing directory")
opt, args = parser.parse_args()
p = work(opt.directory)
p.getAtt()
if __name__ == '__main__':
main()
页:
[1]