Skip to content
Tinbox

tutorials

How to import Gmail into a self-hosted database you own

September 14, 2026

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

Your Gmail is years of data you can read but cannot query. It is excellent mail software, but every message lives in Google's database behind Google's UI. Importing it makes the data yours: rows you can SELECT, search, and back up.

Gmail is genuinely good. The search is fast, the spam filtering is the best in the business, and it almost never goes down. This is not an argument that Gmail is bad. It is an argument that the mail itself, the actual messages, should be data you own and can query directly, not data trapped behind a vendor's API that you rent access to.

This walks the full path from a Google account to mail-as-rows in a database you control: the three on-ramps you can use, why the import has to run locally first, how to actually run it, and how to confirm the result is queryable and not just a dead archive. Where the deep mechanics live in sibling articles (the OAuth dance, the IMAP plumbing), this points to them rather than repeating them.

Why does "owning" your mail mean having it as data?

Owning your mail means it lives as rows in a database you control, not as records behind a vendor's UI you can only reach through their API. The difference is the difference between reading and querying. In Gmail you can open a message and search by keyword, but you cannot run an arbitrary SELECT, join it against your own tables, compute a number across ten years of it, or hand the raw bytes to your own code without going back through Google's API and quota.

Concretely, "data you own" means:

  • The messages are in your SQLite/D1 database, on your Cloudflare account, exportable as one file.
  • Every message is a row with typed columns: from, date, subject, body_text, folder, message_id.
  • You can run SELECT count(*) FROM messages WHERE "from" LIKE '%@stripe.com' and get an answer in milliseconds, no API key, no quota.
  • The body text is in a full-text index you control, so search is a query, not a vendor feature.

The argument for why that matters (legally and practically, beyond convenience) is in why your mail shouldn't live in a third party's database. This article is about the mechanics of making the move.

What are the three on-ramps: Gmail, IMAP, and mbox?

There are three realistic ways to get mail out of Google and into your own store, and the right one depends on what kind of access you have:

On-rampUse whenAuthNotes
Gmail APIYou have a live Google account and want labels mapped cleanlyOAuth (gmail.readonly)Best fidelity; format=RAW gives exact bytes
Generic IMAPA non-Google mailbox, or Gmail with IMAP enabledApp passwordWorks against Fastmail, Dovecot, old work accounts
Google Takeout mboxYou already have an export on disk and no live accessNoneOne giant file; no server round-trips

A rule of thumb: if the account is live and you can authenticate, use the Gmail API (cleanest label/thread mapping). If it is a non-Google box or you would rather not touch Google's API, use IMAP. If you have already run Google Takeout and have a .mbox sitting on disk (for example, the account is closed), parse the mbox directly.

All three converge on the same destination: the same schema, the same Message-ID dedupe key, the same rows. You are not choosing three different products, just three readers for the same target. For the wider menu of on-ramps beyond Gmail, the ways to import your old email into a self-hosted inbox and the overlapping ways to import email into a self-hosted stack survey the options when your mail lives somewhere other than Google.

The Gmail-API path has real friction around OAuth (creating a Desktop client, the consent screen, scopes), covered end to end in importing Gmail locally over OAuth instead of trusting a SaaS. The IMAP path has its own sharp edges (PEEK fetches, UID-vs-Message-ID, folder mapping), covered in importing an IMAP mailbox into a database you own. The mbox path is covered in importing a Google Takeout mbox into your own inbox. The rest of this article is about the architecture they share and how to run the import.

Why does the import run locally first?

The fetch runs on your own machine, and only the final bulk-insert touches the deployment. This is a deliberate architectural choice with two reasons behind it: trust and timeouts.

  Gmail API / IMAP / mbox
            │
            ▼
  ┌───────────────────────┐
  │  local CLI on YOUR     │   auth + pagination + large-mailbox handling
  │  machine (tinbox CLI)  │   raw MIME fetched here, never on a server
  └───────────┬───────────┘
              │  thin, idempotent bulk-insert (HTTPS)
              ▼
  ┌───────────────────────┐
  │  Worker bulk-insert    │   validates + writes rows
  └───────────┬───────────┘
              ▼
        D1 (messages)  +  R2 (attachment bytes)

Trust. The whole reason to leave a SaaS is to stop handing third parties access to your mail. A hosted importer would have you grant it an OAuth refresh token or your IMAP password, then stream your entire mailbox through its servers. Running the fetch locally removes that middleman entirely: your token or app password lives in a file on your own machine, and the message bytes go from Google straight to your laptop straight into your own database. The deployment never sees your Gmail credentials.

Timeouts. Pulling tens of thousands of messages is a multi-minute (sometimes multi-hour) job. That is far longer than a Cloudflare Worker request budget, and there are no Cloudflare Workflows or hosted background-migration jobs in the loop here. So the long-running part stays on your machine, where it can take as long as it needs, and the only thing the deployment exposes is a thin, fast, idempotent bulk-insert API. The Worker's job is just "validate these rows and write them," which finishes in milliseconds per batch.

This is the actual Tinbox importer architecture: CLI fetches locally, Worker only bulk-inserts. It is worth being precise about that because it is easy to assume "cloud import" means a button you click and a server does everything. Here, your laptop does the heavy lifting on purpose.

How do you authenticate to Gmail?

You authenticate either with OAuth (gmail.readonly scope) for the Gmail API or with an app-specific password for IMAP. Both run locally, and Google makes both slightly annoying on purpose, so do not expect to paste your normal login password and have it work.

For the Gmail API, you do the OAuth 2.0 authorization-code flow on your own machine: the consent redirect lands on a localhost port your CLI is listening on, and you exchange the code for tokens stored on disk. The read-only gmail.readonly scope is all you need, and for a personal unverified app you add yourself as a test user. The full Google Cloud console setup is in the local Gmail OAuth walkthrough.

For IMAP, you need an app-specific password, not your account password. Gmail (and Fastmail, Yahoo, and most hosts) reject your real password over IMAP. For Gmail specifically you must enable IMAP in settings and have 2FA on to generate an app password. If you skip this, you will hit the failure in the next section.

Step 1: run the importer

Run a single command and the CLI fetches your mail locally, then bulk-inserts it. The Gmail-API variant:

npx tinbox import gmail --user you@gmail.com

On first run it opens the OAuth consent in your browser, you approve the read-only scope, and the fetch begins. A trimmed-but-real log looks like this:

tinbox import gmail
→ authenticating you@gmail.com (local OAuth, gmail.readonly) ... ok
→ listing messages ........................................ 18,442 ids
→ fetching raw MIME (local) [████████████████████] 18,442/18,442
→ parsing + offloading attachments to R2 ................. 1,204 files
→ bulk-inserting into D1 (batches of 500) ................ 37 batches
   inserted: 18,440   deduped: 2   failed: 0
✓ imported 18,440 messages into inbox "hello" in 6m 11s

The IMAP variant (any mailbox, with an app password) and the mbox variant (an export already on disk) land in the exact same place:

# generic IMAP, with an app-specific password in the environment
IMAP_APP_PASSWORD=… npx tinbox import imap \
  --host imap.gmail.com --user you@gmail.com --inbox hello

# a Google Takeout export, no credentials needed
npx tinbox import mbox --file ./takeout.mbox --inbox hello

The failure you will probably hit first

If you try IMAP with your normal Google password, you get this, not a successful import:

$ IMAP_APP_PASSWORD='my-normal-password' npx tinbox import imap \
    --host imap.gmail.com --user you@gmail.com --inbox hello
→ connecting imap.gmail.com:993 (TLS) ... ok
→ authenticating you@gmail.com ...
✗ AUTHENTICATIONFAILED [ALERT] Application-specific password required
  https://support.google.com/accounts/answer/185833

This is not a bug, it is Google refusing basic-password auth over IMAP. The fix is to generate an app-specific password (with 2FA enabled and IMAP turned on in Gmail settings) and use that instead:

# generate at https://myaccount.google.com/apppasswords , then:
IMAP_APP_PASSWORD='abcd efgh ijkl mnop' npx tinbox import imap \
  --host imap.gmail.com --user you@gmail.com --inbox hello
# → authenticating you@gmail.com ... ok
# → fetching raw MIME (local) ...

(The Gmail-API path sidesteps this entirely because it uses OAuth, not a password. If you would rather avoid app passwords altogether, prefer import gmail.)

Step 2: verify your mail is queryable

After the import, confirm the mail is rows you can query, not just bytes you stored. Because the destination is a real SQLite database (D1 is SQLite under the hood), you can point any SQLite client at it and count.

# how many messages landed, and from when to when?
npx tinbox sql "SELECT count(*) AS n,
                       datetime(min(date)/1000,'unixepoch') AS oldest,
                       datetime(max(date)/1000,'unixepoch') AS newest
                FROM messages"
 n      | oldest              | newest
--------+---------------------+---------------------
 18440  | 2014-03-02 09:41:00 | 2026-06-18 17:22:00

Two things to check in that output, because they are how you know the import was faithful and not flattened:

  • The date range spans your real history. If oldest is today, the importer stamped import time instead of the header Date, and your timeline collapsed. A correct import preserves the original Date so 2014 mail reads as 2014 mail.
  • The count roughly matches Gmail's "All Mail" total. A large gap means a folder or label was skipped.

Peek a single thread to confirm threading survived:

npx tinbox sql "SELECT date, \"from\", subject
                FROM messages
                WHERE thread_id = (SELECT thread_id FROM messages
                                   WHERE subject LIKE '%invoice%' LIMIT 1)
                ORDER BY date"

Replies grouped with their parent (resolved from In-Reply-To/References, not the subject line) means the structure came over intact, not just the individual messages.

Step 3: search what you imported with FTS5

Run a full-text query to confirm the body text is indexed and searchable, not merely stored. The importer populates a SQLite FTS5 index over subject and body, so search is a MATCH query against your own database, no vendor API:

npx tinbox sql "SELECT date, \"from\", subject
                FROM messages_fts
                WHERE messages_fts MATCH 'refund AND (stripe OR paypal)'
                ORDER BY rank
                LIMIT 10"

That this returns results at all is the proof the mail is genuinely yours: the same query would be impossible against Gmail without going through Google's API and quota. The full-text setup (tokenizers, ranking, keeping the index in sync) is its own topic, covered in full-text searching the mail you just imported.

How do you handle big mailboxes and resume an interrupted import?

The importer streams, batches, and dedupes idempotently, so a large mailbox imports incrementally and an interrupted run is safe to re-run. The three properties that make this work:

  • Streaming, not buffering. Messages are fetched and processed one at a time, so a 60,000-message account does not load 8 GB into memory and get OOM-killed at message 40,000. Memory stays flat regardless of mailbox size.
  • Per-message error isolation. In any real mailbox a handful of messages have malformed encodings or a charset the parser cannot handle. Each message is parsed in its own try/catch: a bad one is counted and logged, and the run continues. That is why the log above can show failed: 0 or failed: 3 without ever aborting.
  • Idempotent inserts on the Message-ID. Every row is keyed on the RFC 5322 Message-ID with ON CONFLICT DO NOTHING. Run the import twice, get disconnected halfway and re-run, or run it again next month to top up: you never get a duplicate. For old mail with no Message-ID, a deterministic id is synthesized from the message content so even those dedupe correctly on a re-run.

Because re-running is safe, "resuming" after a dropped connection is just running the command again: already-imported messages dedupe out instantly and only the remainder is written. The mechanics of the dedupe key and synthetic-id generation are detailed in the IMAP import walkthrough.

The honest caveat: there is no hosted background job pacing this for you across days. The fetch runs while your CLI is running. For an enormous archive you run it, let it finish (or re-run after a drop), and that is the whole loop.

What this is NOT: a live Gmail sync

This is an import, not a continuous two-way sync, and it is worth being explicit so you set the right expectation. The import reads your Gmail and writes rows into your own database. It does not:

  • push changes back to Gmail (archiving a message in your copy does nothing in Gmail),
  • watch Gmail for newly arrived mail in real time, or
  • keep the two stores reconciled automatically.

To pick up mail that arrived since your last import, you run the import again. Idempotency makes that cheap and safe: only new messages are written. If what you actually want is new mail flowing into your own stack going forward, that is a different mechanism (receiving on your own domain), not this importer. This tool is for getting the existing archive out of Google and into rows you own.

Once the mail is imported, reading it day to day in a webmail UI you host is the next piece, covered in reading the imported mail in a webmail inbox you host. And if you are coming from a marketing tool rather than a personal mailbox, the related path for importing your marketing list, not just raw mail gets your audience out cleanly too.

Skip the plumbing: one command per source

Everything above is the importer Tinbox already ships, and it runs the way this article describes: the fetch happens locally on your machine, so your Gmail OAuth token or IMAP app password never transits a server, and the messages stream into your own D1 through the same tested bulk-insert path that the IMAP and mbox importers use.

# live Google account, over OAuth
npx tinbox import gmail --user you@gmail.com

# any IMAP mailbox, with an app password
npx tinbox import imap --host imap.example.com --user you@example.com --inbox hello

# a Google Takeout export already on disk
npx tinbox import mbox --file ./takeout.mbox --inbox hello

One implementation reads all three sources into one schema, dedupes on Message-ID (synthesizing one when a message lacks it), preserves the original header Date, maps labels and folders to a direction, resolves threads from In-Reply-To/References, and pushes attachment bytes to R2 while keeping only the key in D1. The CLI does the long-running fetch; the deployment only exposes the thin idempotent insert. That single-implementation-for-every-source design is the point: you migrate a whole account once and the result is queryable, searchable mail you own.

This is one move in leaving a hosted mail provider. For the stack the imported mail lands in (the inbox, the sender, the search), see the full self-hosted Tinbox stack.

Deploy this yourself: npx tinbox init yourdomain.com, then npx tinbox import gmail --user you@gmail.com. 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. See the docs for the per-source flags and the verify queries above.

Frequently asked questions

How do I import my Gmail into a database I own?

Choose one of three sources: the Gmail API over OAuth, IMAP with an app password, or a Google Takeout mbox export. Fetch each message's raw RFC822 bytes locally, parse the MIME, and upsert into your own database keyed on the RFC 5322 Message-ID so re-runs do not duplicate. Run the fetch on your own machine, not a server, so your credentials never leave your laptop and a large mailbox cannot time out a serverless function. With Tinbox the whole flow is one command: tinbox import gmail --user you@gmail.com.

Is importing Gmail this way a live two-way sync?

No. This is a one-time or periodic copy, not a continuous sync. It reads your mail and writes rows into your own database; it does not push changes back to Gmail and it does not watch Gmail for new mail in real time. To pick up mail that arrived since the last run, run the import again. Because every insert is idempotent on the Message-ID, re-running only adds what is new and never duplicates what is already there.

Does the importer handle large mailboxes without falling over?

Yes, because the fetch runs locally and streams. It pages through messages one at a time instead of buffering the whole mailbox into memory, isolates per-message parse failures so one bad message does not abort the run, and writes in batches. Idempotent inserts on the Message-ID make an interrupted run safe to re-run: it tops up from where it effectively left off rather than duplicating. A 60,000-message account imports the same way a 30-message test box does, just slower.

What happens to attachments when I import Gmail?

Attachment bytes are written to object storage (Cloudflare R2) and only the metadata (filename, size, MIME type, content hash, and the R2 key) is stored in the message row. A 20 MB PDF does not belong in a row you scan on every list query, so the bytes live in blob storage and the row holds a pointer. The Tinbox importer offloads attachments to R2 automatically; a hand-rolled importer should do the same.

Why does the import run locally instead of in the cloud?

Two reasons: trust and timeouts. Running the fetch on your own machine means your Gmail OAuth token or IMAP app password never transits a third party's servers, which is the whole point of leaving a SaaS. It also sidesteps serverless time limits: pulling tens of thousands of messages can take many minutes, far longer than a Worker request budget, so the long-running fetch belongs on your laptop while the deployment only exposes a thin, fast, idempotent bulk-insert endpoint.

Can I import from a generic IMAP server or an mbox file, not just Gmail?

Yes. The same import lands mail from three sources into one schema: the Gmail API, any generic IMAP server (Fastmail, Dovecot, an old work account) with an app password, and a Google Takeout mbox file. Use the Gmail or IMAP path for a live account and the mbox path when you already have an export on disk. All three produce the same queryable rows keyed on Message-ID.