Search code examples
c#reporting-servicesmhtml

Convert MHTML to HTML using C#


I was tasked to embed a mHtml into an email body. The issue is that mhtml is not a normal html file so I cannot embed it directly to the email.

How can I do to convert the mhtml into a html file?

Thanks


Solution

  • I found the solution on this link :

    Original (Dead) Link

    Archived Link

    The solution was to extract the HTML encoded as Base64 inside the MHTML.

    var decoded_text = new StringBuilder();
    using (var reader = new StreamReader(mhtFile))
    {
        while (!reader.EndOfStream)
        {
            var line = reader.ReadLine();
            if (line != "Content-Transfer-Encoding: base64") continue;
     
            reader.ReadLine(); //chew up the blank line
            while ((line = reader.ReadLine()) != String.Empty)
                if (line != null)
                    decoded_text.Append(line);
            break;
        }
        return Encoding.UTF8.GetString(
                   Convert.FromBase64String(decoded_text.ToString())));
    }
    

    EDIT: Fixed to support diacritics letters in html suggested by Otas