Skip to content
Tinbox

tutorials

How to import an IMAP mailbox into a database you own

September 16, 2026

#imap#email-migration#sqlite#self-hosted-email#tinbox
Message history moves across a paper bridge between two archives.

You have years of mail sitting on an IMAP server (a host you are leaving, an old work account, a Fastmail or Dovecot box) and you want it in a database you control, with threads and folders intact, not flattened into a dead archive. IMAP makes this harder than it should be.

IMAP is a 1990s protocol that was designed for clients to browse a remote mailbox, not for you to bulk-export it. Every part of an import has a sharp edge: the fetch verb that silently marks all your mail as read, the UIDs that look like stable keys but are not, the messages with no Message-ID, the attachments that bloat your rows. This walks the full manual import end to end with real Node code and the real failures, then shows the local-fetch shortcut at the end.

We will import into SQLite because it is the obvious "database you own" target (it is one file, it runs anywhere, and it is what Cloudflare D1 is under the hood), but the logic is the same for Postgres or anything else.

How do you connect to an IMAP server from Node?

Use a maintained IMAP client (imapflow is the current one), connect on port 993 with TLS, and authenticate with an app password rather than your account password. IMAP itself is a line protocol; you do not want to speak it by hand.

Install the two libraries that do the heavy lifting: an IMAP client to fetch, and a MIME parser to turn raw bytes into fields.

npm install imapflow mailparser better-sqlite3
// connect.js
import { ImapFlow } from "imapflow";

const client = new ImapFlow({
  host: "imap.example.com",
  port: 993,
  secure: true,            // implicit TLS on 993
  auth: {
    user: "you@example.com",
    pass: process.env.IMAP_APP_PASSWORD, // an app-specific password, not your login
  },
  logger: false,           // imapflow logs every command at info by default
});

await client.connect();
const mailboxes = await client.list();
for (const box of mailboxes) {
  console.log(box.path, box.specialUse ?? "");
}
await client.logout();

Two things to get right before you fetch a single byte:

  • Use an app password. Gmail, Fastmail, Yahoo, and most hosts require an app-specific password for IMAP and will reject (or rate-limit and then lock) your real password. For Gmail you also need IMAP enabled in settings and 2FA on to generate one. If you see AUTHENTICATIONFAILED despite a correct password, this is almost always why.
  • Read specialUse. That field tells you which mailbox is \Sent, \Drafts, \Trash, \Junk. You need it to map a Sent mailbox to outbound mail later. Do not guess from the name: "Sent", "Sent Items", "Enviados", and "[Gmail]/Sent Mail" are all the same role with different labels.

A successful run prints something like:

INBOX
[Gmail]/Sent Mail \Sent
[Gmail]/Drafts \Drafts
[Gmail]/All Mail \All
[Gmail]/Trash \Trash
Receipts

Why fetch raw MIME instead of the parsed body IMAP offers?

Fetch the full raw source with FETCH BODY.PEEK[], not IMAP's pre-parsed body parts. The raw RFC822 bytes are the source of truth: they keep every header (Message-ID, References, DKIM signatures), they parse reliably with one well-tested parser, and you can re-parse them later if your parser improves. Reconstructing a message from IMAP's BODYSTRUCTURE part-by-part is where imports quietly corrupt encodings and lose inline images.

The critical detail is the .PEEK. There are two ways to ask for a message body, and one of them mutates your mailbox:

FETCH 1 BODY[]        → returns the body AND sets the \Seen flag
FETCH 1 BODY.PEEK[]   → returns the body and changes nothing

If you fetch with plain BODY[], you will mark every message in the account as read. For an archive you are migrating, that may be merely annoying; for a live account you still use, it is destructive. Always use PEEK. As a second safety net, open the mailbox read-only so the server refuses flag changes entirely:

// imapflow: { readOnly: true } issues EXAMINE instead of SELECT
const lock = await client.getMailboxLock("INBOX", { readOnly: true });

Here is the fetch loop. imapflow exposes source as the raw RFC822 buffer when you ask for { source: true }, which under the hood is the BODY.PEEK[] fetch:

// fetch.js
import { ImapFlow } from "imapflow";

const client = new ImapFlow({
  host: "imap.example.com",
  port: 993,
  secure: true,
  auth: { user: "you@example.com", pass: process.env.IMAP_APP_PASSWORD },
  logger: false,
});

await client.connect();

const lock = await client.getMailboxLock("INBOX", { readOnly: true });
try {
  // "1:*" = every message. fetch() streams, so we never hold the whole box in memory.
  for await (const msg of client.fetch("1:*", {
    uid: true,
    envelope: true,
    source: true,            // the raw bytes, via BODY.PEEK[]
    internalDate: true,
  })) {
    const raw = msg.source;  // Buffer of the full .eml
    // ... parse + store (next sections)
    console.log(`uid ${msg.uid}, ${raw.length} bytes`);
  }
} finally {
  lock.release();
}

await client.logout();

The for await matters. A mailbox can hold tens of thousands of messages; fetch() streams them one at a time so you process and store as you go instead of buffering an 8 GB mailbox into RAM and getting OOM-killed at message 40,000.

How do you parse raw MIME into structured fields?

Run the raw bytes through a MIME parser to get headers, text and HTML bodies, and decoded attachments. MIME parsing by hand is a genuine rabbit hole (quoted-printable, base64, nested multipart/alternative inside multipart/mixed, charset conversion), so use a parser for the import even if you write your own later.

// parse.js
import { simpleParser } from "mailparser";

export async function parse(raw) {
  const p = await simpleParser(raw);

  return {
    messageId: p.messageId ?? null,             // "<abc@host>"
    inReplyTo: p.inReplyTo ?? null,
    references: normalizeRefs(p.references),    // -> string[]
    from: p.from?.value?.[0]?.address ?? "",
    fromName: p.from?.value?.[0]?.name ?? "",
    to: (p.to?.value ?? []).map((a) => a.address),
    subject: p.subject ?? "",
    date: p.date ? p.date.getTime() : null,     // header Date, epoch millis
    text: p.text ?? null,
    html: p.html || null,                       // false when absent -> null
    attachments: (p.attachments ?? []).map((a) => ({
      filename: a.filename ?? "unnamed",
      mimeType: a.contentType,
      size: a.size,
      content: a.content,                       // Buffer of the decoded bytes
      contentId: a.cid ?? null,                 // for inline cid: images
    })),
  };
}

// references can arrive as a string or an array; normalize to an array
function normalizeRefs(refs) {
  if (!refs) return [];
  return Array.isArray(refs) ? refs : [refs];
}

A couple of edge cases this already handles, and that hand-rolled parsers usually miss:

  • p.references comes back as a bare string when there is exactly one reference and an array when there are several. Normalize it or your threading logic breaks on single-reply chains.
  • p.html is false (not undefined) when a message has no HTML part. The || null guards against writing the literal false into your column.
  • internalDate from IMAP and the Date: header are different timestamps. Senders lie or have skewed clocks; keep the header Date for display ordering (it is what the user remembers) but you can store the IMAP internalDate as a tiebreaker.

If you want to drop mailparser and own the parsing too, the encoding and multipart cases are covered in parsing raw MIME email in JavaScript.

How do you store imported mail without creating duplicates?

Key every insert on the RFC 5322 Message-ID and use INSERT ... ON CONFLICT DO NOTHING. The Message-ID is globally unique per message, so a UNIQUE index on it makes the whole import idempotent: run it twice, get interrupted halfway and re-run, top up with newer mail later, and you never get a duplicate row.

Set up the schema with the Message-ID as the natural dedupe key:

CREATE TABLE messages (
  id           TEXT PRIMARY KEY,        -- your own id (nanoid/ksuid)
  message_id   TEXT UNIQUE,             -- RFC 5322 Message-ID: the dedupe key
  in_reply_to  TEXT,
  "references"  TEXT,                    -- JSON array
  "from"        TEXT NOT NULL,
  from_name    TEXT,
  "to"          TEXT NOT NULL DEFAULT '[]',
  subject      TEXT NOT NULL DEFAULT '',
  body_text    TEXT,
  body_html    TEXT,
  folder       TEXT NOT NULL DEFAULT 'inbox',
  direction    TEXT NOT NULL DEFAULT 'inbound',
  date         INTEGER,                 -- header Date, epoch millis
  imported_at  INTEGER NOT NULL
);

Then the upsert. The ON CONFLICT (message_id) DO NOTHING is the entire idempotency story:

// store.js
import Database from "better-sqlite3";
import { createHash } from "node:crypto";
import { nanoid } from "nanoid";

const db = new Database("mail.db");

const insert = db.prepare(`
  INSERT INTO messages
    (id, message_id, in_reply_to, "references", "from", from_name, "to",
     subject, body_text, body_html, folder, direction, date, imported_at)
  VALUES
    (@id, @messageId, @inReplyTo, @references, @from, @fromName, @to,
     @subject, @text, @html, @folder, @direction, @date, @importedAt)
  ON CONFLICT (message_id) DO NOTHING
`);

export function store(parsed, { folder, direction }) {
  const messageId = parsed.messageId ?? synthesizeId(parsed);
  const info = insert.run({
    id: nanoid(),
    messageId,
    inReplyTo: parsed.inReplyTo,
    references: JSON.stringify(parsed.references),
    from: parsed.from,
    fromName: parsed.fromName,
    to: JSON.stringify(parsed.to),
    subject: parsed.subject,
    text: parsed.text,
    html: parsed.html,
    folder,
    direction,
    date: parsed.date,
    importedAt: Date.now(),
  });
  return info.changes === 1 ? "inserted" : "deduped";
}

// Old/migrated mail sometimes has NO Message-ID. Build a deterministic one
// so a re-run still dedupes to the same row instead of inserting again.
function synthesizeId(p) {
  const h = createHash("sha256")
    .update(`${p.from}|${p.date}|${p.subject}|${p.text ?? ""}`)
    .digest("hex");
  return `<imported-${h}@import.local>`;
}

Two traps people fall into here:

  • Do not key on IMAP UIDs. A UID looks like a perfect stable identifier, but it is unique only within one mailbox and only until UIDVALIDITY changes (which happens when a mailbox is recreated or migrated server-side). Key on the Message-ID, which travels with the message everywhere.
  • Handle missing Message-IDs deterministically. A surprising amount of old mail, and most mbox-exported mail, has no Message-ID header. If you generate a random id for those, a re-run duplicates them all. Hash the stable content instead, as above, so the synthetic id is reproducible.

How do you keep folders, dates, and threads intact?

Map each IMAP mailbox to a folder and direction, preserve the original header Date, and resolve threads from the In-Reply-To / References headers rather than the subject line. These three choices are the difference between a faithful import and a flat pile of mail dumped at import time.

Folders and direction. Walk the mailbox list, use specialUse to find the Sent box, and pass the right mapping into store():

function folderFor(box) {
  switch (box.specialUse) {
    case "\\Sent":   return { folder: "sent",    direction: "outbound" };
    case "\\Drafts": return { folder: "drafts",  direction: "outbound" };
    case "\\Junk":   return { folder: "spam",    direction: "inbound"  };
    case "\\Trash":  return { folder: "trash",   direction: "inbound"  };
    default:          return { folder: "inbox",   direction: "inbound"  };
  }
}

Dates. You already kept parsed.date (the header Date) in the schema. That is what makes the imported timeline read in historical order. If you had instead stamped Date.now() on every row, all ten years of mail would collapse to the minute you ran the import and the inbox would be useless.

Threads. Replies belong with their parents. Store in_reply_to and references, and resolve the thread by looking for any already-imported message whose message_id appears in this message's reference chain. Never thread on the subject: "Re: lunch?" matches a hundred unrelated conversations. The full thread-resolution design (and why it is a graph, not a tree) is in designing a D1 email schema for an inbox.

Wiring it all into one loop:

// import.js
import { ImapFlow } from "imapflow";
import { parse } from "./parse.js";
import { store } from "./store.js";

const client = new ImapFlow({
  host: "imap.example.com", port: 993, secure: true,
  auth: { user: "you@example.com", pass: process.env.IMAP_APP_PASSWORD },
  logger: false,
});

await client.connect();
let inserted = 0, deduped = 0, failed = 0;

for (const box of await client.list()) {
  const map = folderFor(box);
  const lock = await client.getMailboxLock(box.path, { readOnly: true });
  try {
    for await (const msg of client.fetch("1:*", { source: true, uid: true })) {
      try {
        const parsed = await parse(msg.source);
        store(parsed, map) === "inserted" ? inserted++ : deduped++;
      } catch (e) {
        failed++;                       // keep going; log the uid for retry
        console.error(`parse/store failed for uid ${msg.uid}:`, e.message);
      }
    }
  } finally {
    lock.release();
  }
}

await client.logout();
console.log({ inserted, deduped, failed });

The try/catch around each message is not optional. In any large mailbox a handful of messages will have malformed encodings, truncated bodies, or a charset your parser cannot handle. Let one bad message abort the whole run and you will be debugging at 3 a.m. on import number six. Catch, count, log the UID, and move on; you can revisit the failures afterward.

What about attachments and the things that break at scale?

Push attachment bytes to blob storage and keep only metadata in the row, and expect the long tail of IMAP quirks (rate limits, connection drops, charset failures) to surface once you run against a real account. The 30-message test mailbox always works; the 60,000-message production account is where you learn what is missing.

The attachment rule is the same one that applies to any inbox database: a 20 MB PDF does not belong in a row you scan on every list query. Write the bytes to object storage (R2, S3, a directory) under a content hash, and store the key plus filename/size/mime in a separate attachments table. The full pattern, including signed retrieval, is in storing email attachments in R2.

The quirks that bite real imports:

  • Rate limits and connection caps. Gmail throttles IMAP and caps simultaneous connections (15 per account); hammer it and you get Too many simultaneous connections and temporary lockouts. Use a single connection, fetch sequentially, and add a small delay between mailboxes.
  • Connections drop mid-import. A multi-hour fetch will hit a dropped socket. You need to resume from where you stopped, which means tracking the last processed UID per mailbox and reconnecting, not restarting from zero. (Idempotency makes a full restart safe but slow.)
  • Charset and encoding failures. Messages labeled iso-2022-jp or with a lying Content-Type charset will throw in the parser. The per-message try/catch keeps these from killing the run.
  • \Recent and read state. Even with PEEK, be aware that some servers expose \Recent and other volatile flags. Read-only mailbox opens (above) are the clean guarantee that nothing changes server-side.

None of this is hard individually. It is the accumulation (PEEK, app passwords, UID-vs-Message-ID, synthetic ids, per-message error isolation, attachment offloading, resume-on-drop, rate limits) that makes a from-scratch IMAP importer a multi-day project instead of an afternoon.

Skip the IMAP plumbing: import with one command

Everything above is the importer Tinbox already ships, and it runs the same way: the fetch happens locally on your machine, so your IMAP credentials never transit a server, and the messages stream into your own database through the same tested ingest path that live mail uses.

tinbox import imap \
  --host imap.example.com \
  --user you@example.com \
  --inbox hello

Under the hood that does exactly what this article built, correctly: it opens the connection read-only, fetches each message's raw MIME with BODY.PEEK[], parses it, dedupes on Message-ID (synthesizing one when a message lacks it), maps Sent mailboxes to outbound/sent, preserves the original header Date, resolves threads from In-Reply-To / References, and pushes attachment bytes to R2 while keeping only the key in D1. It chunks the upload and retries dropped batches, and because every insert is idempotent on the Message-ID, you can re-run it after an interruption with no duplicates.

The design decision that makes it safe: the CLI fetches locally and the Worker only exposes a thin, idempotent bulk-insert API. Your laptop talks to the IMAP server; the deployment never sees your IMAP password. The same tinbox import command also reads Gmail, an mbox export, and a Mailchimp audience, all landing in the same schema. If you are migrating a whole account rather than one mailbox, that one-implementation-for-every-source design is the point.

This is one piece of leaving a hosted mail provider. For the surrounding moves, see the full self-hosted Tinbox stack and the wider set of ways to import your old email into a self-hosted stack, which covers the Gmail, mbox, and Mailchimp paths alongside IMAP. If you want the menu of import sources at a glance before you pick one, the importer tools roundup lays them side by side.

Deploy this yourself: npx tinbox init yourdomain.com, then tinbox import imap --host … --user … --inbox …. The importer and the bulk-insert schema are part of what the bootstrapper scaffolds, and the importer runs locally on your own machine, so your mail and credentials never leave it.

Frequently asked questions

How do I import an existing IMAP mailbox into a self-hosted email database?

Connect to the IMAP server with a Node client like imapflow, select each mailbox, and fetch every message's raw source with FETCH BODY.PEEK[] (the PEEK form does not set the Seen flag). Parse the raw MIME, then upsert each message into your own database keyed on its RFC 5322 Message-ID so re-runs do not duplicate. Preserve the original header Date for ordering and store attachment bytes outside the row.

Why fetch raw MIME (BODY.PEEK[]) instead of asking IMAP for the parsed body?

Because the raw source is the source of truth and IMAP's BODYSTRUCTURE-based partial fetches are easy to get wrong across encodings and nested multipart. Fetching the full RFC822 with BODY.PEEK[] gives you the exact bytes, lets you re-parse later if your parser improves, and keeps the original headers (Message-ID, References, DKIM) intact. PEEK matters: BODY[] without PEEK marks the message as read on the server.

How do I avoid importing the same email twice?

Key your upsert on the RFC 5322 Message-ID header, which is globally unique per message. Put a UNIQUE constraint on that column and use INSERT ... ON CONFLICT DO NOTHING (or an upsert). For old mail with no Message-ID, synthesize a deterministic one from a hash of from + date + subject + body so a re-run still dedupes to the same row. Do not key on IMAP UIDs: they are per-mailbox and change if the mailbox is recreated.

Will importing mark all my mail as read on the server?

Only if you use the wrong fetch verb. FETCH BODY[] (no PEEK) sets the Seen flag on every message you read. Always use FETCH BODY.PEEK[] for a non-destructive import. A read-only mailbox open (examine instead of select) is a second safety net that prevents any flag changes.

How do I keep email threads and folders intact during an IMAP import?

Store each message's In-Reply-To and References headers and resolve threads from them (not from the subject), so replies group with their parents. Map each IMAP mailbox name to your own folder and direction: a Sent mailbox becomes outbound/sent, everything else inbound/inbox. Preserve the message's real Date header so the timeline stays in historical order rather than collapsing to import time.