从多部分MIME文件中提取内容

4 投票
2 回答
5790 浏览
提问于 2025-04-16 05:14

我有一个文件,这个文件里包含了一张tiff格式的图片和一个xml格式的文档,它们是以多部分的mime格式存放在一起的。
我想从这个文件中提取出图片。
我该怎么做呢?

我有一段代码,但如果文件很大(比如30MB),提取的时间会非常长,几乎是无穷无尽的,所以这样做没什么用。

f=open("content_file.txt","rb")
msg = email.message_from_file(f)
j=0
image=False
for i in msg.walk():
    if i.is_multipart():
        #print "MULTIPART: "
        continue
    if i.get_content_maintype() == 'text':
        j=j+1
        continue
    if i.get_content_maintype() == 'image':
        image=True
        j=j+1
        pl = i.get_payload(decode=True)
        localFile = open("map.out.tiff", 'wb')
        localFile.write(pl)
        continue
        f.close()
    if (image==False):
        sys.exit(0);

非常感谢!

2 个回答

0

我不太明白为什么你的代码会卡住。看起来缩进有点问题,而且打开的文件没有正确关闭。你可能也遇到内存不足的情况。

这个版本对我来说运行得很好:

import email
import mimetypes

with open('email.txt') as fp:
    message = email.message_from_file(fp)

for i, part in enumerate(message.walk()):
    if part.get_content_maintype() == 'image':
        filename = part.get_filename()
        if not filename:
            ext = mimetypes.guess_extension(part.get_content_type())
            filename = 'image-%02d%s' % (i, ext or '.tiff')
        with open(filename, 'wb') as fp:
            fp.write(part.get_payload(decode=True))

(部分内容来自 http://docs.python.org/library/email-examples.html#email-examples

4

解决方案:

def extract_mime_part_matching(stream, mimetype):
"""Return the first element in a multipart MIME message on stream
matching mimetype."""

msg = mimetools.Message(stream)
msgtype = msg.gettype()
params = msg.getplist()

data = StringIO.StringIO()
if msgtype[:10] == "multipart/":

    file = multifile.MultiFile(stream)
    file.push(msg.getparam("boundary"))
    while file.next():
        submsg = mimetools.Message(file)
        try:
            data = StringIO.StringIO()
            mimetools.decode(file, data, submsg.getencoding())
        except ValueError:
            continue
        if submsg.gettype() == mimetype:
            break
    file.pop()
return data.getvalue()

来源: http://docs.python.org/release/2.6.6/library/multifile.html

感谢你的支持。

撰写回答