tutorials
RAG over email: build retrieval-augmented answers over your own archive
October 21, 2026

You have years of mail and a question that the answer is buried somewhere inside it, but searching by keyword and reading 40 threads is the slow path, and pasting your whole inbox into a chatbot is the privacy nightmare path.
Retrieval-augmented generation (RAG) is the third path: find the handful of messages that matter, then let a language model read only those and answer. This guide builds the whole thing by hand on Cloudflare (D1 + an LLM call), honestly, including where keyword retrieval falls short. Then it shows where Tinbox does the same work for you if you would rather not assemble it. For the bigger picture of what this unlocks once it works, see the things RAG over your email unlocks.
What is RAG over email, and do I need a vector database?
RAG over email is retrieval plus generation: a retrieval step selects the few relevant messages from your archive, and a generation step hands only those to an LLM to produce a grounded answer. You do not need a vector database to start. Email is unusually friendly to keyword search because people remember concrete anchors (a vendor name, an invoice number, a person, a project codename), and SQLite's FTS5 full-text engine (built into Cloudflare D1) matches those well. Because retrieval runs locally and only the selected snippets leave your account, RAG is one of the ways to use AI on your email without leaking it.
The reason this matters: the naive alternative, "let the model read my whole mailbox," does not scale. Context windows are finite, you pay per token, and accuracy drops as you stuff in more irrelevant mail. Retrieval keeps the input small, the cost flat, and the answer anchored to specific messages you can cite.
The pipeline has three moving parts:
- Index your messages so they are searchable (FTS5).
- Retrieve the top-N messages for a question (bm25 ranking).
- Generate an answer from only those messages (one LLM call).
Embeddings and a vector store are a fourth, optional part. Add them when keyword retrieval demonstrably misses, not before.
How do I build a full-text index over my email in D1?
Create a contentless FTS5 virtual table that mirrors the searchable columns of your messages table, then backfill it. FTS5 is compiled into the SQLite that D1 runs, so there is nothing extra to install.
Assume a messages table like this (trimmed to what retrieval needs):
CREATE TABLE messages (
id TEXT PRIMARY KEY,
thread_id TEXT NOT NULL,
from_addr TEXT NOT NULL,
subject TEXT NOT NULL,
body_text TEXT NOT NULL, -- plain-text version of the email
date INTEGER NOT NULL -- unix seconds
);
Add an FTS5 index over the two text columns. Using content='' (a contentless table) keeps the index small because it stores only the inverted index, not a second copy of every email body:
CREATE VIRTUAL TABLE messages_fts USING fts5(
subject,
body_text,
content='', -- contentless: no duplicated row storage
tokenize='porter' -- porter stemmer: "invoices" matches "invoice"
);
Backfill it from your existing messages. The FTS5 rowid has to be something you can map back to a real message, so store the integer rowid alongside your text id, or use an integer message rowid if you have one. Here we keep a side mapping:
-- One-time backfill. rowid is FTS5's internal key.
INSERT INTO messages_fts(rowid, subject, body_text)
SELECT rowid, subject, body_text FROM messages;
Keep the index current with triggers so new mail is searchable the moment it lands:
CREATE TRIGGER messages_ai AFTER INSERT ON messages BEGIN
INSERT INTO messages_fts(rowid, subject, body_text)
VALUES (new.rowid, new.subject, new.body_text);
END;
CREATE TRIGGER messages_ad AFTER DELETE ON messages BEGIN
INSERT INTO messages_fts(messages_fts, rowid, subject, body_text)
VALUES ('delete', old.rowid, old.subject, old.body_text);
END;
The 'delete' command row is the documented way to remove an entry from a contentless FTS5 table. Forget it and deleted emails keep showing up in search results, which is a subtle, annoying bug to track down later.
How do I retrieve the most relevant emails for a question?
Query the FTS5 table with the question terms, rank with the built-in bm25() function (lower is better), and join back to messages to get the real rows. Retrieve more than you intend to send to the model so you have headroom to filter.
SELECT
m.id,
m.from_addr,
m.subject,
m.body_text,
m.date,
bm25(messages_fts) AS rank
FROM messages_fts
JOIN messages m ON m.rowid = messages_fts.rowid
WHERE messages_fts MATCH ?1 -- the FTS5 query string
ORDER BY rank -- bm25: smaller = more relevant
LIMIT 20;
The bound parameter ?1 is an FTS5 match expression, not raw user text. Passing a user's question straight through breaks the moment someone types a colon, a quote, or the word AND, because those are FTS5 operators. Sanitize by quoting each token so the engine treats them as literal terms:
// Turn free text into a safe FTS5 OR query of quoted terms.
function toFtsQuery(question: string): string {
const terms = question
.toLowerCase()
.match(/[a-z0-9]+/g) ?? [];
if (terms.length === 0) return '""'; // matches nothing, never throws
// Quote each term, OR them together. Phrase quoting also escapes operators.
return terms.map((t) => `"${t}"`).join(" OR ");
}
Here is the failure you are avoiding. Without sanitizing, a question like What did Acme say about the Q3 "rollout"? produces:
Error: fts5: syntax error near "?"
With toFtsQuery, the same question becomes "what" OR "did" OR "acme" OR "say" OR ..., which FTS5 accepts and ranks sensibly. (Dropping stopwords like "what" and "did" before quoting tightens results further; left in, bm25 down-weights them anyway because they appear everywhere.)
Wire it together in a Worker against D1:
interface RetrievedEmail {
id: string;
from_addr: string;
subject: string;
body_text: string;
date: number;
}
async function retrieve(
db: D1Database,
question: string,
limit = 20,
): Promise<RetrievedEmail[]> {
const ftsQuery = toFtsQuery(question);
const { results } = await db
.prepare(
`SELECT m.id, m.from_addr, m.subject, m.body_text, m.date,
bm25(messages_fts) AS rank
FROM messages_fts
JOIN messages m ON m.rowid = messages_fts.rowid
WHERE messages_fts MATCH ?1
ORDER BY rank
LIMIT ?2`,
)
.bind(ftsQuery, limit)
.all<RetrievedEmail & { rank: number }>();
return results ?? [];
}
This is the honest limit of keyword retrieval: it finds emails that share words with the question. Ask "how did we resolve the billing dispute?" and if the actual thread said "credit memo" and "overcharge" without the word "dispute," bm25 will not surface it. That gap is exactly what embeddings fix, and we will get to when that trade is worth making.
How do I build a grounded prompt from the retrieved emails?
Format the retrieved messages into a compact context block with a stable citation marker per email, trim to a token budget, and pair it with the question. The model should answer only from this block.
Budget matters because retrieval returned 20 candidates but you do not want to send 20 full emails. Send the best handful, truncating long bodies, so the signal is not buried and the bill stays small.
function buildContext(emails: RetrievedEmail[], maxChars = 12_000): string {
const blocks: string[] = [];
let used = 0;
for (let i = 0; i < emails.length; i++) {
const e = emails[i];
const when = new Date(e.date * 1000).toISOString().slice(0, 10);
// Truncate each body so one giant email cannot eat the whole budget.
const body = e.body_text.slice(0, 1_500);
const block =
`[E${i + 1}] From: ${e.from_addr} | Date: ${when}\n` +
`Subject: ${e.subject}\n${body}\n`;
if (used + block.length > maxChars) break;
blocks.push(block);
used += block.length;
}
return blocks.join("\n---\n");
}
The [E1], [E2] markers are load-bearing. They give the model a way to cite a specific email, and they give you a way to map an answer back to a real message id (the index in your emails array). Without stable markers you get a fluent answer you cannot verify, which defeats the purpose of grounding.
How do I call the LLM to answer from only those emails?
Send the context block plus the question with a system instruction that the model must answer only from the provided emails and cite them by marker. Use a model that follows grounding instructions tightly. We use Claude via the Vercel AI SDK, which is what the Tinbox chat agent runs on.
import { createAnthropic } from "@ai-sdk/anthropic";
import { generateText } from "ai";
async function answer(
db: D1Database,
apiKey: string,
question: string,
): Promise<string> {
const emails = await retrieve(db, question);
if (emails.length === 0) {
return "I could not find any emails matching that question.";
}
const context = buildContext(emails);
const anthropic = createAnthropic({ apiKey });
const { text } = await generateText({
model: anthropic("claude-opus-4-8"),
system:
"You answer questions using only the emails provided below. " +
"If the emails do not contain the answer, say so plainly. " +
"Cite the emails you used by their marker, e.g. [E2]. " +
"Do not invent senders, dates, or facts not present in the emails.",
prompt: `Emails:\n\n${context}\n\nQuestion: ${question}`,
});
return text;
}
A real answer comes back grounded and citable:
Acme pushed the Q3 rollout from August 12 to September 2 because their
staging environment was not ready [E2]. They confirmed the new date in
writing and asked for an updated invoice reflecting the slip [E4].
You can now resolve [E2] and [E4] to emails[1].id and emails[3].id and link straight to those messages in your inbox UI. That round-trip (question to answer to the exact source emails) is the whole reason to build RAG instead of pasting mail into a chat window.
Honest failure mode: when the model says it does not know
Grounded prompting means the model will sometimes correctly refuse:
The provided emails discuss the Acme contract and the Q3 rollout, but none
of them mention the renewal price. I do not have enough information to
answer that.
That is the system working. It is far better than a confident hallucinated number. When you see it often, the fix is almost always retrieval, not the prompt: your FTS5 query missed the right emails. Log the questions that produce "I do not know" and look at what should have matched.
When do I actually need embeddings and a vector store?
Add embeddings when keyword retrieval measurably misses semantically related mail, and not before. The signal is concrete: you ask questions whose answers exist in your archive under different words than you searched, and bm25 never surfaces them.
The upgrade is additive, not a rewrite. Keep FTS5 as the fast first pass and add a vector search as a parallel retriever, then merge the two result sets (this is "hybrid retrieval," and it consistently beats either alone):
- Generate an embedding per message at ingest time (an embedding model call), store the vector.
- At query time, embed the question and find nearest neighbors.
- Union the FTS5 hits and the vector hits, dedupe by message id, re-rank, and feed the top of that merged list into the same
buildContextandanswerfunctions above.
On Cloudflare you can store vectors in Vectorize and keep everything else identical. The retrieval interface (retrieve() returning RetrievedEmail[]) does not change, so the generation half of your pipeline is untouched. Most single-person inboxes never need this. Reach for it when you have measured the miss rate, not because a vector DB feels more serious than MATCH.
Skip the build: the Tinbox chat agent does this on your own Cloudflare
Everything above (FTS5 over your messages, retrieval, grounded generation, citations) is already wired up in Tinbox. It runs as a streaming chat agent over your inbox, built on the same Vercel AI SDK and Claude pattern shown here, and it deploys to your own Cloudflare account so your archive never leaves your storage. The agent has tools for searching your mail (the FTS5 retrieval), reading threads, and summarizing, so "what did Acme say about the Q3 rollout?" returns an answer with the source messages attached, no glue code from you.
A few honest caveats so you know what you are getting: the inbox is one brand and domain per deploy today (you run a separate deploy per tenant on the same account, and multi-domain-per-instance is designed but not yet built), and any tool that sends mail on your behalf is git-gated rather than freely enabled. Retrieval and question-answering over your own archive, though, work out of the box.
If you want the AI plumbing without the inbox, the same retrieve-then-generate shape is what powers an MCP server for your email, so an assistant like Claude can run these queries directly. For the deeper search internals, see parsing raw email to get clean body_text into your index in the first place, and designing a D1 schema for an inbox for the table layout the FTS5 index sits on top of. For the broader picture of why an owned inbox is worth running, the Tinbox launch post lays out the case.
Deploy this yourself: npx tinbox init <domain>. The full retrieval-and-chat docs walk through wiring the agent to your own model key and tuning what the agent is allowed to do.
Frequently asked questions
Do I need a vector database to do RAG over my email?
No. For an email archive, keyword retrieval with SQLite FTS5 (built into Cloudflare D1) covers most real questions because people search mail with concrete terms: names, invoice numbers, project codenames. Start with FTS5, measure where it misses, and add embeddings only for the semantic gaps. A vector DB is an optimization, not a prerequisite.
Does RAG over email send my whole inbox to the LLM provider?
No, and that is the point. Retrieval runs locally against your own index and selects a handful of messages. Only those retrieved snippets plus the question go to the model. Your full archive never leaves your storage, and you control exactly which bytes are in each prompt.
How many messages should I put in the LLM context?
Retrieve more than you send (for example, top 20 by relevance), then trim to a token budget that leaves room for the answer. 6 to 12 focused message snippets is usually enough. Sending hundreds of full emails wastes tokens, buries the signal, and degrades answer quality.
Why use FTS5 on D1 instead of a hosted search service?
FTS5 ships inside SQLite, so on Cloudflare D1 it runs in the same database as your messages with no extra service, no extra bill, and no data leaving your account. For a single-tenant inbox the index is small and queries are fast. You only outgrow it when you need cross-language stemming or semantic recall that keyword matching cannot provide.
How is RAG different from just letting the model read my whole mailbox?
Models have finite context and you pay per token, so 'read everything' does not scale past a few hundred emails and gets less accurate as you add noise. RAG narrows the input to the relevant messages first, which keeps cost flat, latency low, and answers grounded in specific mail you can cite.