Convert .eml to JSON
An .eml file is a complete RFC 822 message: headers, one or more
MIME parts, encoded words in the headers, and base64 or quoted-printable
bodies. “Convert it to JSON” means decoding all of that into fields you can
query. Here is the shortest correct path in Node and Python, and the parts that
quietly break when you do it by hand.
One file, Node
postal-mime takes the raw bytes and returns a plain object — no streams, no charset handling on your side.
import { readFile } from "node:fs/promises";
import PostalMime from "postal-mime";
// postal-mime takes the raw bytes; it does not need a Node stream.
const raw = await readFile("message.eml");
const email = await PostalMime.parse(raw);
const json = {
subject: email.subject,
from: email.from,
to: email.to,
date: email.date,
text: email.text,
html: email.html,
attachments: email.attachments.map((a) => ({
filename: a.filename,
mimeType: a.mimeType,
size: a.content.byteLength,
})),
};
console.log(JSON.stringify(json, null, 2)); A directory of them
The batch case is a maildir, a Gmail Takeout, or a support-address export. Two rules: never let one bad file stop the run, and always record why a file failed so you can re-run just those.
import { readdir, readFile, writeFile, mkdir } from "node:fs/promises";
import { join, basename } from "node:path";
import PostalMime from "postal-mime";
const SRC = process.argv[2] ?? ".";
const OUT = "json";
await mkdir(OUT, { recursive: true });
const files = (await readdir(SRC)).filter((f) => f.endsWith(".eml"));
for (const file of files) {
try {
const email = await PostalMime.parse(await readFile(join(SRC, file)));
const out = join(OUT, basename(file, ".eml") + ".json");
await writeFile(out, JSON.stringify({
subject: email.subject,
from: email.from,
to: email.to,
date: email.date,
text: email.text,
html: email.html,
headers: Object.fromEntries(email.headers),
attachments: email.attachments.map((a) => ({
filename: a.filename,
mimeType: a.mimeType,
size: a.content.byteLength,
})),
}, null, 2));
} catch (err) {
// One broken file should not stop a 10,000-file import.
console.error(file, err.message);
}
}
console.log("parsed", files.length, "files ->", OUT); # .eml files out of a maildir (Postfix/Dovecot) — one file per message
find /var/mail/you/Maildir/cur -name '*:2,*' -exec cp {} /tmp/eml/ \;
# or straight out of an export
unzip takeout.mbox.zip && node parse.mjs ./Takeout/Mail One file, Python
Python has a competent MIME parser in the standard library. The two things to
get right: parse from bytes, and pass
policy=default so header encoding is decoded instead of handed
back as =?utf-8?B?…?=.
import email, json, pathlib
from email import policy
raw = pathlib.Path("message.eml").read_bytes()
# policy=default decodes RFC 2047 headers and charsets for you.
msg = email.message_from_bytes(raw, policy=policy.default)
body_text = msg.get_body(preferencelist=("plain",))
body_html = msg.get_body(preferencelist=("html",))
out = {
"subject": msg["subject"],
"from": msg["from"],
"to": msg["to"],
"date": msg["date"],
"text": body_text.get_content() if body_text else None,
"html": body_html.get_content() if body_html else None,
"attachments": [
{"filename": part.get_filename(), "mimeType": part.get_content_type()}
for part in msg.iter_attachments()
],
}
print(json.dumps(out, indent=2, ensure_ascii=False)) What actually goes wrong
- Encoded headers. Subjects and display names arrive as RFC 2047 encoded-words. Parse from bytes with a modern policy (Python) or a library that decodes for you — otherwise you get mojibake in every non-ASCII name.
- Wrong charset on the body. A message can declare
iso-8859-1while containing UTF-8 bytes. Trust the declared charset, but keep the raw part so you can re-decode when a message looks broken. - HTML that is not safe to render. Parsing is not sanitizing. If you show the HTML part in a browser, sanitize it first — it is attacker-controlled input by definition.
- Attachments in memory. A 25 MB attachment becomes a 25 MB buffer per message. On a batch of thousands, stream to disk or object storage instead of collecting them in an array.
When you do not need a parser at all
If the mail is arriving right now rather than sitting in a file, the provider can hand you the parsed message and skip this whole step. An inbound email API accepts the SMTP connection and POSTs JSON — subject, addresses, text, html, attachment metadata, and the SPF/DKIM verdict:
{
"type": "email.received",
"data": {
"from": { "address": "ada@example.com", "name": "Ada Lovelace" },
"to": [{ "address": "support@yourdomain.com" }],
"subject": "Can't update my card",
"text": "Hi — my payment keeps failing…",
"html": "<p>Hi — my payment keeps failing…</p>",
"attachments": [{ "filename": "screenshot.png", "size": 48213 }],
"auth": { "spf": "pass", "dkim": "pass", "dmarc": "pass" }
}
} Keep the raw message retrievable for the cases above (re-rendering, custom heuristics, legal retention), and use the parsed form for everything else.
Receive email as JSON — one MX record, signed webhooks, and the raw MIME kept if you need it.