Skip to content
Tinbox

tutorials

Parse raw MIME email in JavaScript without a heavy library

October 19, 2026

#mime#email-parsing#cloudflare-workers#javascript#tutorial
Highlighted content becomes structured date, order, contact, and key tiles.

You wired up Cloudflare Email Routing, pointed it at a Worker, and now you are holding a ReadableStream of raw RFC 5322 text. mailparser will not install. Here is how to turn that stream into a subject, a plain-text body, an HTML body, and attachments, by hand.

When an email arrives at a Worker through Cloudflare Email Routing, you get the raw message: headers, a blank line, and a body that might be plain text, might be HTML, might be both wrapped in multipart/alternative, and might have a PDF and two inline logos bolted on through multipart/mixed and multipart/related. The Node ecosystem has mailparser for exactly this. It does not run on workerd. So you have two choices: find a runtime-agnostic parser, or understand MIME well enough to parse it yourself. This walks the second path in full, because once you have done it once, the libraries stop being magic.

Why can't I just use mailparser on Cloudflare Workers?

mailparser (and the rest of the Nodemailer family) depend on Node's stream, Buffer, and iconv bindings, none of which exist in the Workers runtime. The install may succeed, but at runtime you will hit one of these:

Error: No such module "node:stream".
  imported from "mailparser/lib/mail-parser.js"
ReferenceError: Buffer is not defined
Error: Cannot find module 'iconv-lite'

You can paper over Buffer with a polyfill and flip on the nodejs_compat flag, but mailparser pulls in a deep tree (streaming state machines, encoding tables, HTML sanitizers) that bloats your Worker bundle and still leans on Node stream semantics that the compat layer only partially fills. For a focused job (inbound webhook, OTP extraction, archiving) you are better off parsing with web-standard primitives: TextDecoder, atob, and Uint8Array. That is what the rest of this article uses. If you want the deeper reason Workers refuse so many mail libraries, see why the edge runtime blocks Node mail tooling.

What does a MIME email actually look like?

A MIME message is a tree. The root has headers and a body; if the body is multipart/*, it contains child entities separated by a boundary string, and each child is itself a full MIME entity with its own headers and body. Here is a realistic message with a text part, an HTML part, and one attachment:

From: alice@example.com
To: bob@example.net
Subject: Q3 numbers
Date: Tue, 01 Jul 2026 10:14:22 +0000
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="OUTER"

--OUTER
Content-Type: multipart/alternative; boundary="INNER"

--INNER
Content-Type: text/plain; charset=utf-8
Content-Transfer-Encoding: quoted-printable

Hi Bob,=0A=0AHere are the Q3 numbers. Revenue was =E2=82=AC18,420.
--INNER
Content-Type: text/html; charset=utf-8
Content-Transfer-Encoding: quoted-printable

<p>Hi Bob,</p><p>Revenue was =E2=82=AC18,420.</p>
--INNER--
--OUTER
Content-Type: application/pdf; name="q3.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="q3.pdf"

JVBERi0xLjQKJeLjz9MKMyAwIG9iago8PC9UeXBlL1BhZ2UvUGFyZW50IDEg...
--OUTER--

Four things in that example are where naive parsers break:

  1. Nesting. multipart/mixed contains a multipart/alternative. You cannot split on a single boundary; you have to recurse, and each level has its own boundary.
  2. Quoted-printable. =E2=82=AC is the three bytes of a UTF-8 euro sign. =0A is a newline. A trailing = would be a soft line break. You decode to bytes first, then to text.
  3. Base64 with line wrapping. The PDF is base64 split across many 76-character lines. You must strip the newlines before decoding.
  4. The closing marker. --OUTER-- (boundary plus trailing --) ends the multipart. Miss it and you treat the epilogue as a body part.

How do I split headers from the body?

Split the raw message at the first blank line. Headers end at the first occurrence of \r\n\r\n (or \n\n for non-conformant mail); everything before is the header block, everything after is the body.

function splitHeadersAndBody(raw) {
  // Normalize lone \n to \r\n so the split is predictable, but keep the
  // body bytes intact below by splitting on the original instead.
  const sep = raw.indexOf("\r\n\r\n");
  if (sep !== -1) {
    return { headerText: raw.slice(0, sep), body: raw.slice(sep + 4) };
  }
  // Fallback for messages that use bare LF.
  const sep2 = raw.indexOf("\n\n");
  if (sep2 !== -1) {
    return { headerText: raw.slice(0, sep2), body: raw.slice(sep2 + 2) };
  }
  return { headerText: raw, body: "" };
}

One real-world subtlety: header folding. Long header values are split across lines, and continuation lines begin with a space or tab. You must rejoin them before parsing, or a long Subject or Content-Type will be truncated.

function parseHeaders(headerText) {
  // Unfold: a line starting with space/tab continues the previous one.
  const unfolded = headerText.replace(/\r\n[ \t]+/g, " ");
  const headers = {};
  for (const line of unfolded.split("\r\n")) {
    const idx = line.indexOf(":");
    if (idx === -1) continue;
    const name = line.slice(0, idx).trim().toLowerCase();
    const value = line.slice(idx + 1).trim();
    // Some headers repeat (Received, etc); keep the last for our purposes,
    // but collect Content-* and addressing headers as single values.
    headers[name] = name in headers ? `${headers[name]}, ${value}` : value;
  }
  return headers;
}

How do I read the Content-Type and find the boundary?

Parse the Content-Type header into a media type plus a bag of parameters; the boundary parameter is what separates multipart sections. Parameters can be quoted, and values can themselves contain semicolons inside quotes, so a naive split(";") is not quite right, but it is close enough for the overwhelming majority of mail. Here is a tolerant version:

function parseContentType(value = "text/plain") {
  const parts = splitParams(value);
  const type = parts.shift().trim().toLowerCase();
  const params = {};
  for (const p of parts) {
    const eq = p.indexOf("=");
    if (eq === -1) continue;
    const k = p.slice(0, eq).trim().toLowerCase();
    let v = p.slice(eq + 1).trim();
    if (v.startsWith('"') && v.endsWith('"')) v = v.slice(1, -1);
    params[k] = v;
  }
  return { type, params };
}

// Split on semicolons that are not inside double quotes.
function splitParams(value) {
  const out = [];
  let cur = "";
  let inQuotes = false;
  for (const ch of value) {
    if (ch === '"') inQuotes = !inQuotes;
    if (ch === ";" && !inQuotes) {
      out.push(cur);
      cur = "";
    } else {
      cur += ch;
    }
  }
  out.push(cur);
  return out;
}

With that, parseContentType('multipart/mixed; boundary="OUTER"') gives you { type: "multipart/mixed", params: { boundary: "OUTER" } }.

How do I split a multipart body on its boundary?

Split the body on --<boundary>, discard the preamble before the first boundary and the epilogue after the closing --<boundary>--, and treat each remaining chunk as its own MIME entity. The trick is that the real delimiter on the wire is \r\n--<boundary>, and the closing one has a trailing --.

function splitMultipart(body, boundary) {
  const delimiter = `--${boundary}`;
  // Prepend a newline so the first boundary at position 0 still matches.
  const sections = ("\r\n" + body).split(`\r\n${delimiter}`);
  // sections[0] is the preamble (often empty); drop it.
  sections.shift();
  const parts = [];
  for (let chunk of sections) {
    // The closing boundary is "--boundary--"; its chunk starts with "--".
    if (chunk.startsWith("--")) break;
    // Each chunk begins with \r\n right after the boundary line.
    if (chunk.startsWith("\r\n")) chunk = chunk.slice(2);
    parts.push(chunk);
  }
  return parts;
}

Now the parser is just recursion. Parse an entity into headers and body; if it is multipart, split and recurse; otherwise it is a leaf you decode.

function parseEntity(raw) {
  const { headerText, body } = splitHeadersAndBody(raw);
  const headers = parseHeaders(headerText);
  const ct = parseContentType(headers["content-type"]);

  if (ct.type.startsWith("multipart/") && ct.params.boundary) {
    const children = splitMultipart(body, ct.params.boundary)
      .map(parseEntity);
    return { headers, contentType: ct, children };
  }

  return {
    headers,
    contentType: ct,
    body: decodePart(body, headers, ct),
  };
}

How do I decode quoted-printable and base64 in JavaScript?

Decode the leaf body's bytes according to its Content-Transfer-Encoding, then turn those bytes into text with TextDecoder using the part's charset. The order matters: you decode the transfer encoding to raw bytes first, because a multibyte UTF-8 character like the euro sign is split across several =XX escapes.

function decodePart(body, headers, ct) {
  const cte = (headers["content-transfer-encoding"] || "7bit").toLowerCase();
  const charset = (ct.params.charset || "utf-8").toLowerCase();

  let bytes;
  if (cte === "base64") {
    bytes = base64ToBytes(body);
  } else if (cte === "quoted-printable") {
    bytes = quotedPrintableToBytes(body);
  } else {
    // 7bit / 8bit / binary: the body is already the bytes, latin1-style.
    bytes = Uint8Array.from(body, (c) => c.charCodeAt(0) & 0xff);
  }

  // Attachments stay as bytes; text parts get decoded to a string.
  if (ct.type.startsWith("text/")) {
    try {
      return new TextDecoder(charset).decode(bytes);
    } catch {
      return new TextDecoder("utf-8").decode(bytes); // unknown label fallback
    }
  }
  return bytes; // Uint8Array for binary parts
}

function quotedPrintableToBytes(input) {
  // 1. Remove soft line breaks: "=" at end of a line.
  const noSoft = input.replace(/=\r?\n/g, "");
  const out = [];
  for (let i = 0; i < noSoft.length; i++) {
    const ch = noSoft[i];
    if (ch === "=") {
      const hex = noSoft.slice(i + 1, i + 3);
      if (/^[0-9A-Fa-f]{2}$/.test(hex)) {
        out.push(parseInt(hex, 16));
        i += 2;
        continue;
      }
    }
    out.push(ch.charCodeAt(0) & 0xff);
  }
  return Uint8Array.from(out);
}

function base64ToBytes(input) {
  // Strip CRLF and whitespace that base64 wrapping inserts every 76 chars.
  const clean = input.replace(/[^A-Za-z0-9+/=]/g, "");
  const bin = atob(clean); // atob exists in workerd
  return Uint8Array.from(bin, (c) => c.charCodeAt(0));
}

atob and TextDecoder are both available in the Workers runtime, which is why this works at the edge with zero dependencies and no nodejs_compat flag.

Putting it together in a Worker email handler

Cloudflare Email Routing hands your Worker a message object with a raw ReadableStream. Read it to a string (preserving bytes as latin1 so multibyte content survives until you decode it), then parse.

export default {
  async email(message, env, ctx) {
    const raw = await streamToBinaryString(message.raw);
    const tree = parseEntity(raw);

    const subject = decodeHeaderWord(tree.headers["subject"] || "");
    const text = findPart(tree, "text/plain");
    const html = findPart(tree, "text/html");
    const attachments = collectAttachments(tree);

    // do something with it: store, classify, webhook out...
    console.log({ subject, hasHtml: !!html, attachments: attachments.length });
  },
};

async function streamToBinaryString(stream) {
  const reader = stream.getReader();
  let bin = "";
  for (;;) {
    const { done, value } = await reader.read();
    if (done) break;
    for (const byte of value) bin += String.fromCharCode(byte);
  }
  return bin;
}

function findPart(node, type) {
  if (node.children) {
    for (const c of node.children) {
      const found = findPart(c, type);
      if (found) return found;
    }
    return null;
  }
  return node.contentType.type === type ? node.body : null;
}

function collectAttachments(node, out = []) {
  if (node.children) {
    for (const c of node.children) collectAttachments(c, out);
    return out;
  }
  const disp = (node.headers["content-disposition"] || "").toLowerCase();
  const isAttachment =
    disp.startsWith("attachment") || node.contentType.params.name;
  if (isAttachment) {
    out.push({
      filename:
        node.contentType.params.name ||
        parseContentType(disp).params.filename ||
        "unnamed",
      type: node.contentType.type,
      bytes: node.body, // Uint8Array
    });
  }
  return out;
}

There is one more decode you will need almost immediately: encoded-words in the headers. A Subject with non-ASCII text arrives as =?utf-8?Q?Q3_n=C3=BCmbers?= or =?utf-8?B?...?=. That is RFC 2047, a quoted-printable or base64 chunk wrapped in =?charset?encoding?...?=. A minimal decoder:

function decodeHeaderWord(value) {
  return value.replace(
    /=\?([^?]+)\?([bBqQ])\?([^?]*)\?=/g,
    (_, charset, enc, text) => {
      const bytes =
        enc.toLowerCase() === "b"
          ? base64ToBytes(text)
          : quotedPrintableToBytes(text.replace(/_/g, " "));
      try {
        return new TextDecoder(charset).decode(bytes);
      } catch {
        return text;
      }
    },
  );
}

Where does this hand-rolled parser still bite you?

It works for ordinary mail, but production inbound is a hostile input surface, and a 120-line parser leaves gaps. The honest list of what is still missing:

  • Content-Type parameters split with RFC 2231 continuations (filename*0, filename*1*) for long or non-ASCII filenames. Common from Outlook.
  • Bare \n line endings mixed with \r\n in the same message. Some senders are inconsistent and your boundary split silently misses parts.
  • Boundaries that appear as a substring inside a part's content. Rare but real; you have to match boundaries only at line starts.
  • multipart/related and cid: rewriting so inline images render. You have the bytes via Content-ID; mapping them into the HTML is more work.
  • Malformed base64, missing charsets, lying Content-Transfer-Encoding values, and 30 MB attachments that you do not want to hold in a string in a 128 MB Worker.
  • Header injection and address parsing (To/From/Cc with display names, groups, and comments) which is its own RFC 5322 grammar.

None of these are unsolvable. All of them are the kind of thing you discover from a bug report at 2am because one sender does something weird. That is the cost of owning the parser: it is yours, including the edge cases.

The shortcut: a parser that is already tested against real mail

Or skip all of this. Tinbox runs entirely on your own Cloudflare account (D1, R2, Queues, and Workers), and the inbound side ships a MIME parser that already handles the list above: nested multipart, quoted-printable, base64, RFC 2047 encoded-words, RFC 2231 filename continuations, charset fallbacks, cid: inline images mapped to R2 objects, and oversized attachments streamed to R2 instead of buffered. It is the same parser that feeds the webmail inbox, full-text search, and the email interpreters that classify inbound mail.

npx tinbox init yourdomain.com

That scaffolds the Worker, provisions the storage, and wires Cloudflare Email Routing to the inbound handler. Inbound mail arrives already parsed into a structured message (subject, decoded text and HTML bodies, attachments in R2), so your application code never touches a boundary string. From there you can turn parsed mail into an inbound webhook or run OTP and verification-code extraction on top of it. For more of what becomes possible once mail is structured, these email interpreter recipes for smarter inbound handling are a good catalog.

If you only need parsing today, write the version above; it is genuinely enough for a focused job and you will understand your mail far better for having done it. When the long tail of broken senders starts filing bugs, that is the signal to stop maintaining a MIME parser as a side project.

Deploy this yourself: npx tinbox init yourdomain.com. The inbound parser and email handler are documented in the Tinbox docs under inbound mail.

Frequently asked questions

How do I parse a raw MIME email in JavaScript?

Split the raw message at the first empty line (\r\n\r\n) into a header block and a body. Unfold folded header lines, then parse each into name/value pairs. Read Content-Type to find the boundary, split the body on that boundary into parts, and recurse. For each leaf part, decode the bytes according to its Content-Transfer-Encoding header: quoted-printable, base64, or 7bit/8bit as-is.

Can I use mailparser or nodemailer to parse email on Cloudflare Workers?

No. mailparser depends on Node streams and Buffer, which the Workers runtime (workerd) does not provide. You either bring a runtime-agnostic parser or write the parsing yourself using web-standard APIs: TextDecoder, atob, and Uint8Array.

How do I decode quoted-printable encoding in JavaScript?

Remove soft line breaks (an = at the end of a line), then replace every =XX sequence with the byte whose hex value is XX. Collect the resulting bytes into a Uint8Array and decode with TextDecoder using the charset from the part's Content-Type.

What charset should I decode an email part with?

Use the charset parameter from that part's Content-Type header (for example text/plain; charset=utf-8). If it is absent, default to utf-8 for modern mail, but be aware legacy mail may use iso-8859-1 or windows-1252, which TextDecoder supports by label.

Where do inline images live in a MIME message?

Inline images are usually parts inside a multipart/related container, encoded as base64, with a Content-ID header. HTML bodies reference them via cid: URLs. To render them you map each Content-ID to its decoded bytes and rewrite cid: references to data URLs or stored object URLs.