Skip to content
Tinbox

tutorials

Import an mbox file into your own inbox

September 18, 2026

#mbox#email-migration#google-takeout#importers#tutorial
Message history moves across a paper bridge between two archives.

Google Takeout finished. You now have a 4.2 GB file called All mail Including Spam and Trash.mbox and nothing that opens it. Double-clicking does nothing useful. Here is how to turn that file into real, searchable, threaded messages in a database you own.

The mbox format is older than most of the people using it. It is what you get when you export a mailbox from Google Takeout, Thunderbird, Apple Mail, or any Unix mail tool: a single plain-text file with every message concatenated one after another. It is simple enough to parse in an afternoon and just irregular enough that a naive parser will quietly mangle a fraction of your mail. This walks the full manual path first (the real edge cases, the escaping bug everyone hits, the threading problem), then shows the one-command shortcut at the end.

How do I open a Google Takeout mbox file?

You do not open an mbox file, you import it. An mbox is an archive format, not a document, so there is no "reader" for it the way there is for a PDF. You have two practical options: import it into a mail client that understands mbox (Thunderbird with the ImportExportTools NG add-on is the usual route), or parse it programmatically and load it into your own store. This article does the second, because importing into another desktop client just moves the lock-in around. If you want years of mail to be queryable, searchable, and owned, you want it in a database.

First, confirm what you actually have. A Takeout Mail export unzips to one .mbox file (Google flattens all labels into a single file, with an X-Gmail-Labels header per message recording which labels applied). Check the size and the first message before you write any code:

ls -lh "Takeout/Mail/All mail Including Spam and Trash.mbox"
# -rw-r--r--  1 you  staff   4.2G  Jun 18 09:14  All mail...mbox

# Peek at the first separator and headers without loading the file
head -c 2000 "Takeout/Mail/All mail Including Spam and Trash.mbox"
From 1729384756123456789@xxx Mon Jun 18 09:14:02 +0000 2026
X-GM-THRID: 1729384756123456789
X-Gmail-Labels: Inbox,Important
Delivered-To: you@gmail.com
Received: by 2002:a05:... with SMTP id ...
Date: Mon, 18 Jun 2026 09:14:02 +0000
From: Alice <alice@example.com>
To: you@gmail.com
Subject: Q3 numbers
Message-ID: <CAH7q1=abc123@mail.example.com>
Content-Type: multipart/alternative; boundary="000000000000abcd"

That first line, From 1729384756..., is the mbox separator. Everything from one From line up to the next From line is one message.

What is the structure of an mbox file, exactly?

An mbox file is messages concatenated together, each introduced by a "From " line: the literal word From, a space, an envelope address, and a timestamp. This line is not part of the message; it is the delimiter. The four things that make mbox parsing harder than "split on From " are:

  1. The separator is ambiguous. A line inside a message body can legitimately start with From (think: "From here on, we agree to..."). The mbox format handles this by escaping such lines at write time, and you must un-escape at read time.
  2. There is no length prefix. You cannot seek; you have to scan line by line and detect each new separator. For a 4 GB file that means streaming, not readFileSync.
  3. Line endings vary. Mail uses \r\n; some tools write \n. Your separator detection has to tolerate both.
  4. The first line of the file is a separator, but there is no blank line before it, so your "new message" detection needs to handle position zero.

The escaping convention has two flavors. mboxo escapes any body line beginning with From . mboxrd (the more robust one, and what Google and most modern tools emit) escapes any line beginning with zero or more > followed by From . So From becomes >From , and an already-escaped >From becomes >>From . To reverse it cleanly under mboxrd, you strip exactly one leading > from any line matching >*From .

How do I split an mbox into individual messages?

Stream the file line by line and start a new message at every line that matches the separator pattern /^From .*\d{4}/ or, more simply, /^From / at a message boundary. Accumulate the lines in between as one raw message. Here is a streaming splitter in Node that handles a multi-gigabyte file without loading it into memory:

import { createReadStream } from "node:fs";
import { createInterface } from "node:readline";

// Yields one raw RFC 822 message (string) per mbox entry.
async function* splitMbox(filePath) {
  const rl = createInterface({
    input: createReadStream(filePath, { encoding: "latin1" }),
    crlfDelay: Infinity, // treat \r\n as a single line break
  });

  let current = null; // lines of the message in progress

  // The separator: "From " + sender + a date ending in a 4-digit year.
  // Anchoring on the trailing year avoids matching a body line that is
  // literally "From here..." (those never carry a date).
  const isSeparator = (line) => /^From .*\b\d{4}\b\s*$/.test(line);

  for await (const line of rl) {
    if (isSeparator(line)) {
      if (current) yield unescapeMboxrd(current.join("\n"));
      current = []; // start a fresh message; drop the separator line itself
    } else if (current) {
      current.push(line);
    }
    // lines before the very first separator (rare junk) are ignored
  }
  if (current) yield unescapeMboxrd(current.join("\n"));
}

// Reverse mboxrd escaping: strip one leading ">" from ">*From " lines.
function unescapeMboxrd(message) {
  return message.replace(/^>(>*From )/gm, "$1");
}

Two decisions worth calling out. Reading as latin1 preserves every byte exactly (one byte per character) so that base64 and quoted-printable survive intact until you decode them properly during MIME parsing; reading as utf8 here would corrupt any non-UTF-8 byte. And anchoring the separator regex on a trailing four-digit year is a pragmatic guard against false positives, because a real body line that begins with From almost never ends in a bare year. It is not bulletproof (the escaping is the real fix), but it catches the cases the escaping misses, such as mbox files written by buggy tools that did not escape.

How do I parse each message and avoid duplicates?

Parse each raw message as MIME to extract the subject, date, text and HTML bodies, and attachments, then key it on the Message-ID header so re-running the import never duplicates. The MIME parsing is its own topic with its own sharp edges (nested multipart, quoted-printable, encoded-word subjects); if you are writing that part yourself, the standalone guide to parsing raw MIME in JavaScript covers it in full. Assume you have a parseEmail(raw) that returns { messageId, date, from, to, subject, text, html, attachments }.

The part specific to importing is idempotency. You will re-run this import. The upload will get interrupted at message 31,402 of 80,000, or you will wonder whether it finished and run it again, or you will want to top up with newer mail later. So every message needs a stable natural key:

import { createHash } from "node:crypto";

function dedupeKey(parsed) {
  // RFC Message-ID is the right key and is unique per message.
  if (parsed.messageId) return parsed.messageId.trim();

  // Some old, forwarded, or draft mail has no Message-ID. Synthesize a
  // deterministic one so re-imports still collapse to the same record.
  const basis = [
    parsed.from || "",
    parsed.date || "",
    parsed.subject || "",
    createHash("sha256").update(parsed.text || parsed.html || "").digest("hex"),
  ].join("�");
  const h = createHash("sha256").update(basis).digest("hex");
  return `<imported-${h}@import.local>`;
}

The critical rule: dedupe on Message-ID, never on file offset or insertion order. A position-based key duplicates the entire mailbox on every re-run, which is the single most common mbox-import failure. With a Message-ID key, your insert becomes an upsert, and a re-run is a no-op for messages that already exist.

How do I rebuild threads from an mbox?

Threads come from headers, not from the order messages appear in the file. Each reply carries In-Reply-To (its parent's Message-ID) and References (the full Message-ID chain back to the root of the conversation). You reconstruct the tree by walking those references, which means a reply can be imported before its parent and still thread correctly once both rows exist.

A minimal thread-resolution strategy:

// Given a parsed message and a lookup of already-seen Message-ID -> threadId,
// decide which thread this message belongs to.
function resolveThread(parsed, threadByMessageId) {
  const refs = parseReferenceHeaders(parsed); // In-Reply-To + References, ordered
  for (const ref of refs) {
    const existing = threadByMessageId.get(ref);
    if (existing) return existing; // join the parent's thread
  }
  // No known ancestor yet: this message starts (or provisionally starts) a thread.
  return newThreadId();
}

function parseReferenceHeaders(parsed) {
  const ids = [];
  // In-Reply-To is usually a single id; References is a space-separated chain.
  const grab = (h) => (h || "").match(/<[^>]+>/g) || [];
  ids.push(...grab(parsed.inReplyTo));
  ids.push(...grab(parsed.references));
  return [...new Set(ids)];
}

The honest caveat: out-of-order imports mean you sometimes create a thread for a reply, then later import its parent, and the two should merge. A robust importer does a second pass to reconcile, or stores references eagerly and resolves threads lazily on read. Subject-line matching (stripping Re: and Fwd: and grouping) is a tempting shortcut but it false-merges unrelated conversations with generic subjects like "Hi" or "Question", so treat it as a last resort, not the primary signal.

What about dates, folders, and attachments?

Preserve the original Date header as the message's timestamp so history sorts correctly; do not stamp every imported message with "now". A common mistake is setting the message date to import time, which collapses ten years of mail into a single afternoon and makes the inbox useless. Keep two timestamps if your schema allows: the real header Date (for ordering and display) and a separate receivedAt or importedAt (set to now, for audit).

For folders, a Gmail Takeout flattens everything into one file but records the original labels in the X-Gmail-Labels header. Read it to reconstruct Inbox vs Sent vs Archive. Mail in the Sent label should be marked outbound; everything else is inbound. For attachments, decode them out of the MIME and store the bytes in blob storage (object storage, a filesystem, S3, R2), keeping only the key in your database. Holding a 25 MB attachment as a base64 string in a row is how you blow up a database. If you are on Cloudflare, storing email attachments in R2 is the natural target.

Putting the manual pipeline together:

async function importMbox(filePath, store) {
  const threadByMessageId = new Map();
  let inserted = 0, deduped = 0, failed = 0;

  for await (const raw of splitMbox(filePath)) {
    try {
      const parsed = parseEmail(raw);
      const key = dedupeKey(parsed);
      if (await store.has(key)) { deduped++; continue; }

      const threadId = resolveThread(parsed, threadByMessageId);
      threadByMessageId.set(key, threadId);

      await store.insert({
        messageId: key,
        threadId,
        date: parsed.date,          // original header date, NOT now
        folder: foldersFromLabels(parsed),
        subject: parsed.subject,
        text: parsed.text,
        html: parsed.html,
        attachments: await store.putBlobs(parsed.attachments),
      });
      inserted++;
    } catch (err) {
      failed++;
      console.error("skip:", err.message); // never let one bad message halt the run
    }
  }
  return { inserted, deduped, failed };
}

The try/catch around each message matters more than it looks. In a real mailbox of 80,000 messages there will be a handful that are truncated, have a malformed boundary, or carry an encoding your parser does not expect. The import must skip them and keep going, then report the failures, not abort at message 12,000 and leave you with a half-loaded inbox.

Where does the hand-rolled importer still bite you?

It works, and you will learn a lot building it, but production mailboxes are a hostile input surface. The gaps a 200-line importer leaves:

  • Separator false positives and false negatives from mbox files written by tools that escaped inconsistently (mboxo vs mboxrd vs mboxcl vs no escaping at all).
  • Out-of-order threading that needs a reconciliation pass, not a single forward scan.
  • Memory pressure if you accidentally buffer the whole file or a giant attachment in a string instead of streaming.
  • Re-run safety across machines and interruptions, which needs the dedupe key enforced as a database constraint, not just an in-memory Set.
  • Charset and encoded-word handling in subjects and filenames (RFC 2047, RFC 2231) that the MIME layer has to get right.
  • Folder and label fidelity, so Sent mail does not show up as inbound and important flags survive.

None of these are unsolvable. All of them are the kind of thing you find out from your own archive at the worst time, after you have deleted the original export.

The shortcut: import an mbox in one command

Or skip all of this. Tinbox runs entirely on your own Cloudflare account (D1, R2, Queues, Workers), and ships the mbox importer as a local CLI command:

npx tinbox import mbox "Takeout/Mail/All mail.mbox" --inbox primary
Splitting mbox... 81,204 messages found
Importing  [████████████████████] 81,204/81,204
  inserted: 80,991   deduped: 0   failed: 213 (malformed, logged)
Done in 6m 41s. Re-run anytime; it is idempotent.

The design decision that matters: the fetch and parse run locally on your machine, not in a Worker. The CLI streams and splits the mbox (handling the From separator and >From un-escaping), parses each message, and POSTs batches to an idempotent bulk-insert API on your deployment. Nothing about your mail transits a Tinbox server; the bytes go straight from your laptop to your own Cloudflare account. The Worker side reuses the exact same ingest path that live inbound mail uses, so imported messages thread correctly (via In-Reply-To and References), preserve their original dates, land attachments in R2 with only the keys in D1, and dedupe on Message-ID. Run it twice and the second run inserts nothing.

The same tinbox import command handles Gmail (local OAuth, no token leaves your machine), any IMAP host, and Mailchimp audiences. If you are coming from a server mailbox rather than a Takeout file, importing an IMAP mailbox into a database you own is the sibling path, and the broader case for getting your mail out of a vendor is in migrating your team off Google Workspace. For the full menu of source formats and which importer fits each, the ways to import your old email into a self-hosted inbox and the broader import-into-a-self-hosted-stack roundup survey the options.

Write the parser above if you want to understand your own archive, it is genuinely a good exercise and a few hundred lines. When the long tail of broken senders and out-of-order threads starts costing you evenings, that is the signal to stop maintaining an mbox parser as a side project.

Deploy this yourself: npx tinbox init yourdomain.com, then tinbox import mbox <file> --inbox <id>. The importers are documented in the Tinbox docs under migration.

Frequently asked questions

What is an mbox file?

An mbox file is a plain-text concatenation of email messages, each prefixed by a 'From ' line (the word From, a space, an envelope sender, and a date). It is the format Google Takeout, Thunderbird, and most Unix mail tools use to export a whole mailbox. One mbox file holds many messages; the 'From ' lines are the only separators between them.

How do I open a Google Takeout mbox file?

A Takeout mbox is not meant to be opened in a viewer; it is an archive format. You import it into a mail client or your own database. You can import it into Thunderbird with the ImportExportTools NG add-on, or parse it programmatically by splitting on the 'From ' separator lines and reading each message as RFC 822. Do not double-click it expecting a reader.

Why does my mbox importer create duplicate messages on a re-run?

Because it keyed on file position or row order instead of a stable natural key. Key every message on its RFC Message-ID header (which is unique per message) so a re-import resolves to the same row and updates instead of inserting. Messages with no Message-ID (some old or forwarded mail) need a deterministic synthetic id derived from sender, date, subject, and a body hash, so they still dedupe.

How are email threads reconstructed from an mbox?

Threads come from headers, not file order. Each reply carries In-Reply-To (the Message-ID of its parent) and References (the Message-ID chain back to the root). You group messages by walking those references, so a reply imported before its parent still lands in the right thread once both exist. Subject matching ('Re:' stripping) is a fragile fallback, not the primary signal.

What is the '>From ' escaping problem in mbox files?

Because a literal 'From ' at the start of a line marks a new message, any real line in a body that begins with 'From ' is escaped to '>From ' when the mbox is written (the mboxrd/mboxo conventions). When you parse, you must reverse this: turn leading '>From ' back into 'From ' inside each message body, or the body is silently corrupted. Failing to un-escape is the most common mbox parsing bug.