Skip to content
Tinbox

tutorials

How to import your Gmail locally with OAuth instead of trusting a SaaS

September 4, 2026

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

You want years of Gmail in a database you control, but every migration tool wants you to grant it OAuth access so it can pull your entire mailbox through its own servers. That is a lot of trust to hand a third party for a one-time copy.

The uncomfortable part of most Gmail importers is not the parsing, it is the access model. You click "Connect Gmail", grant a scope, and now some company holds a refresh token to your whole account and streams every message through their infrastructure. For a one-shot export, that middleman is unnecessary. The Gmail API is a plain HTTPS API, OAuth's authorization-code flow runs fine on your own machine, and there is nothing stopping the fetch from happening entirely on your laptop with the bytes going straight into your own database.

This walks the full local import end to end with real code and the real failure modes: the OAuth dance, the unverified-app warning, format=RAW, base64url decoding, pagination, and quota. Then it shows the one-command shortcut at the end.

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

How do you let an importer read Gmail without it touching a server you do not own?

Run the OAuth authorization-code flow and the Gmail API calls in a local Node process, so the consent redirect lands on localhost and the resulting refresh token is written to a file on your machine. The only parties in the data path are Google and your laptop. No hosted importer, no third-party token store, no mailbox bytes crossing someone else's network.

The mechanics are standard OAuth 2.0, just pointed at your own machine instead of a SaaS callback. You need an OAuth client first.

In the Google Cloud console:

  1. Create (or pick) a project and enable the Gmail API.
  2. Configure the OAuth consent screen. For a personal export, choose External, leave it in Testing, and add your own Google account under Test users. (Testing mode means you do not need Google to verify the app, which it will not do for a personal one-off anyway.)
  3. Create credentials of type OAuth client ID, application type Desktop app. Download the JSON: you want the client_id and client_secret.

A Desktop-app client is the key choice. It is the OAuth client type designed for software running on a user's own machine, and it permits a localhost redirect, which is what lets the whole flow stay local.

How do you run the OAuth flow locally?

Spin up a throwaway HTTP server on a localhost port, open Google's consent URL pointed at that port as the redirect, and exchange the authorization code Google sends back for an access token and a refresh token that you persist to disk. This is the authorization-code flow with localhost as the redirect URI.

Use Google's auth library so you are not hand-rolling token exchange and refresh:

npm install googleapis mailparser better-sqlite3
// auth.js
import http from "node:http";
import { URL } from "node:url";
import fs from "node:fs";
import { google } from "googleapis";

const SCOPES = ["https://www.googleapis.com/auth/gmail.readonly"];
const TOKEN_FILE = "./gmail-token.json";
const PORT = 53682; // any free high port; must match the client config below

export async function authorize() {
  const oauth2 = new google.auth.OAuth2(
    process.env.GMAIL_CLIENT_ID,
    process.env.GMAIL_CLIENT_SECRET,
    `http://localhost:${PORT}`, // the local redirect URI
  );

  // Reuse a saved refresh token if we already have one.
  if (fs.existsSync(TOKEN_FILE)) {
    oauth2.setCredentials(JSON.parse(fs.readFileSync(TOKEN_FILE, "utf8")));
    return oauth2;
  }

  const authUrl = oauth2.generateAuthUrl({
    access_type: "offline",     // ask for a refresh token
    prompt: "consent",          // force the refresh token on re-auth
    scope: SCOPES,
  });

  // Wait for Google to redirect back to localhost with ?code=...
  const code = await new Promise((resolve, reject) => {
    const server = http.createServer((req, res) => {
      const url = new URL(req.url, `http://localhost:${PORT}`);
      const c = url.searchParams.get("code");
      const err = url.searchParams.get("error");
      res.end("You can close this tab and return to the terminal.");
      server.close();
      err ? reject(new Error(err)) : resolve(c);
    });
    server.listen(PORT, () => {
      console.log("Open this URL in your browser:\n" + authUrl);
    });
  });

  const { tokens } = await oauth2.getToken(code);
  oauth2.setCredentials(tokens);
  fs.writeFileSync(TOKEN_FILE, JSON.stringify(tokens, null, 2)); // stays local
  return oauth2;
}

The first run prints a URL. Open it, pick your account, and you will hit the warning that trips people up:

Google hasn't verified this app
This app hasn't been verified by Google yet. Only proceed if you know
and trust the developer.

That is expected and fine. You are the developer, the app is your own Desktop client, and you added yourself as a test user. Click Advanced, then Go to (your app) (unsafe), and grant the read-only scope. The warning exists precisely because an unverified app reading Gmail is exactly the thing you should be suspicious of. Here, the "app" is the script in front of you.

A few things to get right before fetching a byte:

  • Request gmail.readonly, nothing more. It can list and fetch (including format=RAW). An import never needs send or modify scope, and requesting a broader scope just makes the consent screen scarier and the token more dangerous if leaked.
  • access_type: "offline" plus prompt: "consent" is what gets you a refresh token. Without offline access you get a one-hour access token and no way to resume tomorrow.
  • The token file is the sensitive artifact. It contains a refresh token to your mailbox. It lives on your disk, in .gitignore, and nowhere else. That is the whole point of doing this locally.

Why fetch format=RAW instead of Gmail's parsed format?

Fetch each message with users.messages.get?format=RAW, which returns the complete original RFC822 message as a single base64url string. The raw bytes are the source of truth: they carry every header (Message-ID, References, DKIM signatures) and every MIME part exactly as sent. Gmail's default format=full gives you a pre-parsed part tree that you then have to walk and reassemble, and that reassembly is where encodings, nested multipart/alternative, and inline images quietly get corrupted.

The Gmail API does not hand you a mailbox in one call. You list ids, then fetch each message. List is paginated:

// list.js
import { google } from "googleapis";

export async function* listMessageIds(auth) {
  const gmail = google.gmail({ version: "v1", auth });
  let pageToken;
  do {
    const res = await gmail.users.messages.list({
      userId: "me",
      maxResults: 500,       // the API max per page
      pageToken,
      // q: "before:2020/01/01", // optional Gmail search filter to scope the import
    });
    for (const m of res.data.messages ?? []) yield m.id;
    pageToken = res.data.nextPageToken; // undefined on the last page
  } while (pageToken);
}

Then fetch each id as RAW and decode it. The raw field is base64url, not standard base64, so you must swap the URL-safe characters before decoding or you get garbage bytes:

// fetch.js
import { google } from "googleapis";

export async function fetchRaw(auth, id) {
  const gmail = google.gmail({ version: "v1", auth });
  const res = await gmail.users.messages.get({
    userId: "me",
    id,
    format: "RAW",
  });

  // base64url -> base64 -> Buffer of the exact RFC822 bytes.
  const b64 = res.data.raw.replace(/-/g, "+").replace(/_/g, "/");
  const raw = Buffer.from(b64, "base64");

  // labelIds tells us where the message lived; SENT -> outbound mail.
  return { raw, labelIds: res.data.labelIds ?? [] };
}

The base64url-to-base64 swap (- to +, _ to /) is the single most common silent bug in a hand-rolled Gmail importer. If you Buffer.from(res.data.raw, "base64") directly, Node tolerates it just enough to produce subtly wrong bytes on some messages, and you will not notice until a parser chokes deep into the run. Swap the characters first.

How do you parse and store the messages without duplicates?

Run the raw bytes through a MIME parser to get structured fields, then upsert each message keyed on its RFC 5322 Message-ID with INSERT ... ON CONFLICT DO NOTHING. The Message-ID is globally unique per message, so a UNIQUE index on it makes the import idempotent: run it twice, get rate-limited halfway and resume, top up later with newer mail, and you never get a duplicate row.

MIME parsing by hand is a real rabbit hole (quoted-printable, base64, nested multipart, charset conversion), so use a parser for the import even if you write your own later. The encoding cases are covered in parsing raw MIME email in JavaScript if you want to own that step.

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

const db = new Database("mail.db");
db.exec(`
  CREATE TABLE IF NOT EXISTS messages (
    id          TEXT PRIMARY KEY,
    message_id  TEXT UNIQUE,            -- RFC 5322 Message-ID: the dedupe key
    in_reply_to TEXT,
    "references"  TEXT,                   -- JSON array
    "from"        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
  );
`);

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

export async function store(raw, labelIds) {
  const p = await simpleParser(raw);
  const messageId = p.messageId ?? synthesizeId(p);

  // SENT label -> outbound/sent; everything else stays inbound.
  const isSent = labelIds.includes("SENT");

  const info = insert.run({
    id: nanoid(),
    messageId,
    inReplyTo: p.inReplyTo ?? null,
    references: JSON.stringify(
      Array.isArray(p.references) ? p.references : p.references ? [p.references] : [],
    ),
    from: p.from?.value?.[0]?.address ?? "",
    subject: p.subject ?? "",
    text: p.text ?? null,
    html: p.html || null,                 // mailparser returns false when absent
    folder: isSent ? "sent" : "inbox",
    direction: isSent ? "outbound" : "inbound",
    date: p.date ? p.date.getTime() : null, // the header Date, not import time
    importedAt: Date.now(),
  });
  return info.changes === 1 ? "inserted" : "deduped";
}

// Some old mail 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?.text ?? ""}|${p.date}|${p.subject}|${p.text ?? ""}`)
    .digest("hex");
  return `<imported-${h}@import.local>`;
}

Three decisions in there are what separate a faithful import from a flat dump:

  • Key on Message-ID, not the Gmail message id. Gmail's id is per-account and changes if you ever re-import from a different export path; the RFC Message-ID travels with the message everywhere and is the right idempotency key.
  • Preserve the header Date. That is what keeps the timeline in historical order. Stamp Date.now() instead and ten years of mail collapses to the minute you ran the import.
  • Map the SENT label to outbound/sent. Gmail labels are how it models folders; SENT is the one you must special-case so your sent mail does not show up as received. Resolve threads later from In-Reply-To / References, never from the subject line; the schema design is in designing a D1 email schema for an inbox.

How do you stay inside Gmail's API quota?

Pace the fetch: go sequentially or with small bounded concurrency, back off on 429 and 403 rateLimitExceeded, and persist the last page token so an interrupted run resumes instead of restarting. The Gmail API charges per-method quota units against a daily budget and enforces a per-user rate limit, and messages.get is a few units each. A mailbox of 50,000 messages is 50,000 fetches, so unpaced concurrency is how you get throttled.

Here is the whole loop with pacing, error isolation, and resume:

// import.js
import fs from "node:fs";
import { authorize } from "./auth.js";
import { listMessageIds } from "./list.js";
import { fetchRaw } from "./fetch.js";
import { store } from "./store.js";

const CURSOR = "./gmail-cursor.json"; // {seen: [...ids already done]}

const auth = await authorize();
const done = new Set(fs.existsSync(CURSOR) ? JSON.parse(fs.readFileSync(CURSOR, "utf8")).seen : []);

let inserted = 0, deduped = 0, failed = 0;

for await (const id of listMessageIds(auth)) {
  if (done.has(id)) continue; // resume: skip what we already stored
  try {
    const { raw, labelIds } = await withBackoff(() => fetchRaw(auth, id));
    (await store(raw, labelIds)) === "inserted" ? inserted++ : deduped++;
    done.add(id);
  } catch (e) {
    failed++; // keep going; this id can be retried on the next run
    console.error(`failed ${id}:`, e.message);
  }
  if ((inserted + deduped) % 200 === 0) {
    fs.writeFileSync(CURSOR, JSON.stringify({ seen: [...done] }));
    await sleep(50); // gentle pacing between bursts
  }
}

fs.writeFileSync(CURSOR, JSON.stringify({ seen: [...done] }));
console.log({ inserted, deduped, failed });

// Retry on transient rate-limit / 5xx with exponential backoff.
async function withBackoff(fn, tries = 5) {
  for (let i = 0; i < tries; i++) {
    try {
      return await fn();
    } catch (e) {
      const code = e?.code ?? e?.response?.status;
      const retryable = code === 429 || code === 403 || (code >= 500 && code < 600);
      if (!retryable || i === tries - 1) throw e;
      await sleep(2 ** i * 1000); // 1s, 2s, 4s, 8s, 16s
    }
  }
}
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

A real import looks like this in practice:

failed 18f2a...: Quota exceeded for quota metric 'Queries'
$ node import.js   # just run it again; resume skips the 6,200 already stored
{ inserted: 612, deduped: 6203, failed: 0 }

The try/catch around each message and the cursor file are not optional polish. Across a large mailbox you will hit a transient 403, a message with a charset your parser cannot decode, or a dropped connection on hour two. Catch, count, persist the cursor, and let a re-run pick up where you stopped. Idempotency on the Message-ID is what makes a full restart safe; the cursor is what makes resuming fast.

The accumulation is the real cost: the Desktop OAuth client, the localhost flow, the unverified-app warning, format=RAW, the base64url swap, Message-ID dedupe, synthetic ids, SENT-label mapping, per-message error isolation, backoff, and a resume cursor. None is hard alone. Together they make a from-scratch Gmail importer a multi-day project rather than an afternoon, even before you wire in attachments and threading.

Skip the Gmail plumbing: import with one command

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

tinbox import gmail --inbox hello

That command consumes a client id, client secret, and refresh token you already obtained through the local installed-app OAuth flow (GMAIL_CLIENT_ID, GMAIL_CLIENT_SECRET, and GMAIL_REFRESH_TOKEN, or their flags). It does not launch the consent flow itself. It lists your messages, fetches each one with format=RAW, decodes the base64url, parses the MIME, dedupes on Message-ID (synthesizing one when a message lacks it), maps the SENT label 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 because every insert is idempotent on the Message-ID, you can safely run the command again after an interruption without duplicates. The current command starts the local source fetch over on a re-run; it does not persist the tutorial's cursor file for you.

The design decision that makes it trustworthy is structural, not a promise. The CLI fetches locally and the deployment exposes only a thin, idempotent bulk-insert API. Your laptop talks to Google; the Worker never sees your Gmail token. That is the same posture behind owning your email data outright rather than renting access to it. The same tinbox import command also reads an IMAP server, an mbox export, and a Mailchimp audience, all landing in one schema, so if you are moving a whole account the one-implementation-for-every-source design is the point.

If your mail lives on a generic IMAP host rather than Gmail, the parallel path is importing an IMAP mailbox into a database you own. If you only have a Google Takeout export, see importing an mbox file into your own inbox. And if you are leaving the whole Workspace, not just the mailbox, migrating your team off Google Workspace email covers the surrounding moves. For the menu of every source at a glance, the six ways to import old email into a self-hosted inbox and the ways to import email into a self-hosted stack compare the options, and the email migration mistakes that tank deliverability is worth a read before you cut over.

Deploy this yourself: npx tinbox init yourdomain.com, then tinbox import gmail --inbox hello. The importer and the bulk-insert schema are part of what the bootstrapper scaffolds, and the importer runs locally on your own machine, so you can confirm for yourself that nothing leaves it.

Frequently asked questions

How do I import my Gmail mailbox locally over OAuth without sending it through a third party?

Create a Desktop-app OAuth client in the Google Cloud console, run the OAuth 2.0 authorization-code flow on your own machine (the consent screen redirects to a localhost port your script is listening on), and exchange the code for tokens that stay on disk. Then call the Gmail API directly from your local Node process: page users.messages.list for ids and fetch each one with users.messages.get?format=RAW. Decode the base64url raw bytes, parse the MIME, and store it. No server in the middle ever sees your token or your mail.

What OAuth scope do I need to read Gmail for an export?

https://www.googleapis.com/auth/gmail.readonly is enough to list and fetch messages, including format=RAW. It is a read-only, restricted scope, so for an unverified personal app Google will show an unverified-app warning and you add your own account as a test user on the consent screen. You do not need a full gmail scope, and you should not request one for an import.

Why fetch format=RAW instead of the parsed Gmail message format?

format=RAW returns the complete original RFC822 message as one base64url string, which is the source of truth: every header (Message-ID, References, DKIM), every MIME part, and the exact bytes. The default format=full hands you Gmail's pre-parsed part tree, which is more work to reassemble correctly and can lose fidelity on nested multipart and inline images. Fetch RAW, decode base64url to bytes, and run those bytes through one well-tested MIME parser.

Will running my own Gmail importer hit API quotas?

It can if you fire requests with no pacing. The Gmail API bills per-method quota units and enforces a per-user rate limit, and messages.get costs a few units each, so a large mailbox is tens of thousands of calls. Fetch sequentially or with small bounded concurrency, honor 429 / 403 rateLimitExceeded with exponential backoff, and resume from the last page token rather than restarting. A one-shot personal import stays well inside the daily quota if you pace it.

Is it safe to give a Gmail importer my account, and where does my refresh token live?

If the importer runs locally, the only place your refresh token lives is a file on your own machine, and the Gmail bytes go straight from Google to your laptop to your own database. A hosted SaaS importer is the opposite: you grant it a refresh token it stores on its servers, and your whole mailbox transits its infrastructure. Local-first import removes that third party entirely, which is the posture Tinbox's importer is built around.