Parsing a large MBOX in the browser without uploading it
Google Takeout hands you your Gmail as one .mbox file. That file can be several gigabytes, and the attachments are inside it as base64 text. I wanted a page where you pick that file and get a ZIP of the attachments, with
Google Takeout hands you your Gmail as one .mbox file. That file can be several gigabytes, and the attachments are inside it as base64 text. I wanted a page where you pick that file and get a ZIP of the attachments, without the file being uploaded. This is how the parser works and what went wrong along the way.
The code is on GitHub under MIT: opsaflow/takeout-attachment-extractor. Line references below are to that repo.
The constraint: you cannot load the file
await file.text() on a multi-gigabyte file is not an option. Strings have length limits and the tab has a memory budget. So the design has two rules:
- Scan bytes in fixed chunks to find where each email starts and ends.
- Decode one email at a time, and keep only metadata.
The whole thing runs in a Web Worker (src/worker.js) so the page stays responsive.
Pass 1: find message boundaries in bytes
An MBOX is emails concatenated, each preceded by an envelope line such as From 1234@xxx Tue Sep 15 09:00:00 +0000 2026. The scanner slices the File in 1 MiB chunks and walks the bytes looking for newlines.
From src/index.js, lines 20 to 32 (the excerpt stops inside the loop):
for (let offset = 0; offset < file.size; offset += chunkSize) {
const bytes = new Uint8Array(
await file.slice(offset, offset + chunkSize).arrayBuffer()
)
for (let i = 0; i < bytes.length; i++) {
if (bytes[i] !== 10) {
if (prefix.length < 1024) prefix += String.fromCharCode(bytes[i])
continue
}
const line =
lineStart === 0 ? prefix.replace(/^\xEF\xBB\xBF/, '') : prefix
if (envelope.test(line)) {
if (start !== null) yield { start, end: lineStart, number: count }
Two details matter here.
It works on bytes, not decoded text. Mail is not reliably UTF-8, and a decoder would shift offsets. The offsets are used later to slice each message back out of the file, so they have to be exact.
Only the first 1,024 bytes of a line are kept. A base64 attachment can be one very long line in a broken message, and the scanner only needs enough of a line to test it against the envelope pattern. Because state is carried across chunks, an envelope line split between two chunks is still found. The tests run the scanner at many small chunk sizes to prove it.
The output is an async generator of { start, end } byte ranges. Nothing is decoded yet.
Pitfall: "From " inside a body
A body line that starts with From would look like a new message. The mboxrd convention, which Takeout follows, prefixes such lines with >, and adds one more > to lines that already look quoted. The envelope regex is strict (weekday, month, time) to avoid false splits, and the quoting is undone once per message, at byte level.
From src/index.js, lines 59 to 71:
for (let i = 0; i < bytes.length; i++) {
if ((i === 0 || bytes[i - 1] === 10) && bytes[i] === 62) {
let j = i
while (bytes[j] === 62) j++
if (
bytes[j] === 70 &&
bytes[j + 1] === 114 &&
bytes[j + 2] === 111 &&
bytes[j + 3] === 109 &&
bytes[j + 4] === 32
)
removed.push(i)
}
}
It removes exactly one > from lines matching >+From. Doing this on bytes instead of a string keeps 8-bit attachment data intact.
Pass 2: MIME, one email at a time
Each range is sliced, unescaped and handed to postal-mime, which handles the MIME tree: nested multipart, headers, and filename decoding (RFC 2047 encoded words and RFC 2231 filename*= parameters). Emails above 64 MiB encoded are skipped and reported instead of being loaded.
The surprise was byte fidelity. A general MIME parser is built for displaying mail, and its output normalizes line endings in some parts. For an export tool, a file whose bytes changed is a corrupt file. src/mime.js subclasses the parser, records the byte range of each leaf part while lines are processed, then decodes those ranges itself: quoted-printable by hand, raw copy for 7bit, 8bit and binary. It validates base64 strictly, and it rejects a multipart body with no closing boundary, since that usually means a truncated message. A skipped email with a notice is better than a silently damaged PDF. The adapter relies on parser internals, so the version is pinned in the repo.
For each attachment the scan stores name, size, sender, date, subject, a SHA-256 hash and the message's byte range. The decoded bytes are dropped.
Duplicates
The same PDF often arrives many times through replies and forwards. Deduplication uses crypto.subtle.digest('SHA-256', content) over decoded bytes, so it is exact: names do not matter, and a resized image is a different file. It is applied after the other filters, so the first copy inside your selection is the one kept.
Export: go back to the file
Since no bodies are kept, export slices the needed messages again and parses them a second time. That costs CPU, but it bounds memory, and it allows a safety check.
From src/export.js, lines 43 to 53:
for (const row of paths) {
signal?.throwIfAborted()
if (row.range.start !== currentStart) {
mail = await readMessage(file, row.range)
currentStart = row.range.start
}
const attachment = mail.attachments[row.index]
if (!attachment || (await contentHash(attachment.content)) !== row.hash)
throw new Error(
'The archive changed or an attachment could not be verified. Choose the original archive and scan it again.'
)
If the file changed on disk between scan and export, the hash no longer matches and the export stops.
The ZIP is written with zip.js at level: 0. Attachments such as PDFs and JPEGs are already compressed, so storing them is faster and costs little. Where the browser offers showSaveFilePicker, the ZIP streams to disk through a FileSystemFileHandle. Elsewhere it is built as a Blob, capped at 250 MiB of selected data.
Two smaller traps: attachment names come from strangers, so they are sanitized (path separators, control characters, Windows device names, case-insensitive collisions). And the CSV index prefixes cells that start with =, +, - or @, so a spreadsheet does not run a subject line as a formula.
Limits
- 64 MiB per encoded email, 200,000 emails and 100,000 attachments per scan. Past a limit, the result is marked partial.
- Standard Takeout MBOX only. Other MBOX variants, PST and OST are out of scope.
- An attached email stays a single
.eml. Its own attachments are not unpacked. - Encrypted mail is not decrypted.
- I have not published benchmarks. Memory per step is bounded by design, but device memory and disk space still decide what works.
Try it
- Source and tests: github.com/opsaflow/takeout-attachment-extractor
- Hosted version, free, no account: Google Takeout Attachment Extractor
Bug reports are welcome. Please use synthetic messages, not a real mailbox.
Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.