Recursive AI

Extract HTML and images from MHTML in C#

OneMail is a free, open-source email library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

MHTML stores a saved page and its resources in one MIME file. page.mht in the zip contains HTML and an embedded PNG.

Terminal
dotnet add package RecursiveAI.OneMail

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using RecursiveAI.OneMail.Mime.Mhtml;
 
using var page = MhtmlDocument.Open("page.mht")!;
File.WriteAllBytes("page.html",
    page.RootResource!.GetContent()!);
File.WriteAllBytes("pixel.png",
    page.Resolve("pixel.png")!.GetContent()!);
Console.WriteLine(
    "Wrote page.html and pixel.png");

Resolve("pixel.png") uses the sample’s resource name; replace it with a name your HTML references, or list page.Resources.

Text
Wrote page.html and pixel.png

Unzip the example, then dotnet run.

The full program

The sample’s root HTML is <h1>Saved page</h1><img src="pixel.png" alt="Pixel">, with Content-Location: https://example.com/index.html. The second part is image/png, has Content-Location: https://example.com/pixel.png and Content-ID: <pixel>, and contains a base64-encoded one-pixel PNG.

The full program writes every resource to extracted/. It generates names rather than using untrusted resource locations as file paths. It does not rewrite links in the extracted HTML.

C#
using RecursiveAI.OneMail.Mime.Mhtml;
 
using var page = MhtmlDocument.Open("page.mht")
    ?? throw new InvalidDataException("No MHTML document.");
Directory.CreateDirectory("extracted");
int index = 0;
foreach (var resource in page.Resources)
{
    string extension = resource.MediaType switch
    {
        "text/html" => ".html",
        "image/png" => ".png",
        _ => ".bin"
    };
    string name = $"resource-{index++}{extension}";
    byte[] bytes = resource.GetContent()
        ?? throw new InvalidDataException("Part has no content.");
    File.WriteAllBytes(Path.Combine("extracted", name), bytes);
    Console.WriteLine($"{name}: {resource.MediaType}, {bytes.Length} bytes");
}
Console.WriteLine($"Root: {page.RootResource?.AbsoluteLocation}");
Console.WriteLine($"Image: {page.Resolve("pixel.png")?.MediaType}");

dotnet run prints:

Text
resource-0.html: text/html, 52 bytes
resource-1.png: image/png, 68 bytes
Root: https://example.com/index.html
Image: image/png

If no MHTML document is found, the full program throws InvalidDataException; ordinary file-read and file-write errors propagate.

Variations

Resolve a Content-ID instead of a location. This complete snippet finds the same PNG by cid:pixel.

C#
using RecursiveAI.OneMail.Mime.Mhtml;
 
using var page = MhtmlDocument.Open("page.mht")!;
var image = page.Resolve("cid:pixel");
Console.WriteLine(image?.MediaType ?? "Not embedded");
Text
image/png

The short answer

Use MhtmlDocument.Open to view an MHT or MHTML file as a root resource and its embedded resources. RootResource.GetContent() returns the decoded HTML bytes; Resolve("pixel.png") finds the embedded resource named by a reference in that HTML. Save those bytes under filenames you control. Neither operation fetches a remote web page.

Extracting resources is not the same as taking a screenshot, converting a page to a raster image, or downloading everything a website currently serves. This recipe works on the MIME content already stored in the archive. The MHTML documentation describes the resource view and URI-resolution rules.

Can I convert MHTML to HTML?

You can extract the root HTML, but a usable local page may also need its embedded images and stylesheets. In this example, the snippet at the top deliberately saves the image as pixel.png, matching the root’s existing relative reference. The HTML therefore still names the extracted image. The full program instead assigns generated filenames to illustrate extraction of an arbitrary resource list; it does not produce a rewritten, self-contained web page.

For a general converter, retain a mapping from each resource’s content ID and resolved location to its new local name. Rewrite HTML references using that mapping. CSS references require the same care. Do not assume that writing the first HTML part and every attachment under its original name preserves the page’s links. A root can be selected through multipart metadata rather than its position in the file.

MhtmlDocument accepts a multipart/related entity or a lone HTML part. It is a view over the MIME tree, not an HTML renderer, so the extraction does not execute scripts or calculate browser layout.

How do I extract an image from MHT?

Resolve the reference used by the HTML, then call GetContent() on the returned resource. The PNG in this sample uses base64 transfer encoding. GetContent() returns the decoded PNG, not the base64 text; save it as bytes rather than decoding it as a string.

A cid: reference matches a part’s Content-ID, not a Content-Location that happens to contain a cid: URL. The variation above demonstrates that lookup. For location-based references, the library applies the documented base order: the supplied HTML base, legacy Content-Base, absolute content locations, then the fallback base. Exact matches are attempted before normalized URI matching. Duplicate locations select the first resource and report the ambiguity.

A reference can be absent from the archive. Check for a null resolution result in an application handling arbitrary input; do not automatically replace a missing part with a network request. Extracted filenames should not come directly from URLs or content IDs, which can contain separators or collide. The full program’s numbered names keep paths within the chosen output directory.

How can I open an MHTML file?

For programmatic access, open it with MhtmlDocument.Open and dispose the returned document when finished. Use Resources when you need an inventory rather than one known image. Each entry includes its media type, content ID, content location and whether it is the root.

For text, preserve the bytes or decode them using the part’s declared charset rather than assuming every saved page is UTF-8. For binary resources, copy decoded content unchanged. Keep the original MHTML if the archive itself matters: an extraction is a derivative set of files, not a byte-for-byte replacement of the original MIME document.

All onemail recipes