Extracting different content-type of MHT file into multiple mht file

别等时光非礼了梦想. 提交于 2019-12-13 05:14:33

问题


I am writing an mht script to parse an mht file and extract the part message from the parent and write them to a separate mht file

I wrote the below function which opens a mht file at file_location and searches for specific content_id and writes it to a new mht file

def extract_content(self, file_location, content_id,extension):
    first_part = file_location.split(extension)[0]
    #checking if file exists
    new_file = first_part + "-" + content_id.split('.')[0] + extension

    while os.path.exists(new_file):
        os.remove(new_file)

    with open(file_location, 'rb') as mime_file, open(new_file, 'w') as output:
        ***#Extracting the message from the mht file***
        message = message_from_file(mime_file)
        t = mimetypes.guess_type(file_location)[0]

        #Walking through the message
        for i, part in enumerate(message.walk()):

            #Check the content_id if the one we are looking for
            if part['Content-ID'] == '<' + content_id + '>':
                ***witing the contents***
                output.write(part.as_string(unixfrom=False))

Apparently I am not able to open the output parts in IE in the case of application/pdf and application/octet-stream.

How do I write these Content-Type like application/pdf and application/octet-stream in to mht files so that I am able to view the image or pdf in IE?

Thanks


回答1:


Try this:

...
if m['Content-type'].startswith('text/'):
                    m["Content-Transfer-Encoding"] = "quoted-printable"

                else:
                    m["Content-Transfer-Encoding"] = "base64"

                m.set_payload(part.get_payload())                        
                ****Writing to output****
                info = part.as_string(unixfrom=False)
                info = info.replace('application/octet-stream', 'text/plain')
                output.write(info)
...

Tell me if it works.



来源:https://stackoverflow.com/questions/25562803/extracting-different-content-type-of-mht-file-into-multiple-mht-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!