Sample code for 30+ languages & platforms
Java Requires Chilkat v11.0.0+

Create an HTML preview with embedded images

See more Email Object Examples

Make an independent copy of with-attachments.eml, remove ordinary file attachments from the copy, and export its HTML with related images as data URLs. The original retains its attachments. Use a sanitized viewer when showing untrusted HTML.

Chilkat Java Downloads

Java
import com.chilkatsoft.chilkat2.ChilkatException;
import com.chilkatsoft.chilkat2.Email;
import com.chilkatsoft.chilkat2.StringBuilder;

public class ChilkatExample {

    public static void main(String[] args) {
        // Assumes Chilkat is unlocked. See Global Unlock Sample.

        Email email = new Email();
        try {
            email.loadEml("with-attachments.eml");
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        Email preview = new Email();
        try {
            email.makeCopy(preview);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        // Keep related items: the HTML still refers to them.
        preview.dropAttachments();
        System.out.println("Files in original: " + email.getNumAttachments() + "  Files in preview: " + preview.getNumAttachments());
        if (!preview.hasHtmlBody()) {
            System.out.println("This message has no HTML preview.");
            return;
        }

        StringBuilder html = new StringBuilder();
        try {
            preview.getHtmlBodySb(true, html);
        } catch (ChilkatException e) {
            System.out.println(e.getLastErrorText());
            return;
        }

        try {
            html.writeFile("preview.html", "utf-8", false);
        } catch (ChilkatException e) {
            System.out.println("Failed: html.WriteFile.");
            return;
        }

        System.out.println("Saved preview.html.");
    }
}