提取不同的内容类型MHT文件分成多个MHT文件

问题描述:

我写的MHT脚本解析MHT文件,并从母公司中提取部分信息,并将其写入到一个单独的MHT文件提取不同的内容类型MHT文件分成多个MHT文件

我写了下面的这在file_location和搜索特定的content_id打开MHT文件,并将其写入到一个新的MHT文件

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)) 

显然我不能够在IE中应用/ PDF和应用的情况下,打开输出部分功能/ octet-stream

我怎么写这些内容类型如应用/ PDF和 应用程序/八位字节流中的MHT文件,以便我能够查看IE图片或PDF?

感谢

+0

你说你不能打开它。什么是错误信息? – 2014-08-29 06:37:17

+0

@ m170897017感谢您的评论。它不显示任何错误,但显示一个空白页 – karthikbharadwaj 2014-08-29 07:01:57

试试这个:

... 
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) 
... 

告诉我,如果它的工作原理。

+0

感谢您的答案。我可以打印文件以及在文本编辑器中打开文件。但是我希望IE能够将它识别为正确的.mht文件,而不是这样做。我想这是一些格式问题,但我无法准确指出。 – karthikbharadwaj 2014-08-29 07:11:23

+0

@karthikbharadwaj我认为改变标题可能会有所帮助。我已经更新了我的答案。试一试,告诉我。 – 2014-08-29 07:22:03

+0

非常感谢。工作正常。我认为我在内容类型应用程序/八位字节流,基本上是JPG和pdf附件的应用程序/ pdf中遇到了问题。有没有办法对它们进行适当的编码,以便它们出现在新的mht文件中?我也在环顾四周玩代码。如果你有这方面的知识,这将是有益的。谢谢。 – karthikbharadwaj 2014-08-29 08:28:47