tutorials
Handle reply-by-email and keep threads intact
October 26, 2026

You send a notification, a customer hits reply, and the reply lands in your inbox as an orphan with no idea which conversation it belongs to. Threading is not magic; it is three headers and some careful matching. Here is the by-hand version, the edge cases that will bite you, and the shortcut.
Reply-by-email is one of the highest-leverage features in any product that emails people: a support ticket that a customer can answer from their own mail client, a comment notification they can reply to, a digest they can respond to inline. The hard part is not receiving the reply (covered in turning inbound mail into a webhook); it is attaching that reply to the right conversation so your inbox shows a coherent thread instead of a pile of disconnected messages.
Get the headers right and threading is deterministic. Get them wrong and you are guessing from subject lines, which fails the moment two people use the subject "Question" on the same day. Let us build it correctly.
How does email threading actually work?
Threading is driven by three headers: Message-ID, In-Reply-To, and References. Every message you send carries a globally-unique Message-ID. When someone replies, their mail client copies the original Message-ID into In-Reply-To and appends it to a References chain that lists the whole ancestry of the conversation. To thread an inbound reply, you match the IDs in its References (or In-Reply-To) against the Message-ID values you recorded when you sent the original message. A match means the same thread, with certainty.
You send: Message-ID: <root-abc@yourdomain.com>
Customer replies: In-Reply-To: <root-abc@yourdomain.com>
References: <root-abc@yourdomain.com>
You reply again: Message-ID: <reply-def@yourdomain.com>
In-Reply-To: <m-2@customer-mx.com>
References: <root-abc@yourdomain.com> <m-2@customer-mx.com>
The whole scheme falls apart if you never set a Message-ID you control, or you set one but do not store it. So that is step one, and it happens on the way out, not on the way in.
Step 1: Generate and store a Message-ID when you send
Generate a unique, domain-namespaced Message-ID for every outbound message and persist it against the thread before you send. The recipient's reply will echo this exact value back to you, so it is the join key for the entire conversation.
A Message-ID is an RFC 5322 msg-id: an opaque left side, an @, and a domain you control, wrapped in angle brackets. Make the left side unpredictable so IDs cannot be guessed and forged.
// Generate a stable, unique Message-ID for an outbound message.
function newMessageId(domain: string): string {
// crypto.randomUUID() is available in the Workers runtime.
const token = crypto.randomUUID().replace(/-/g, "");
return `<${token}@${domain}>`;
}
// On send: set the header, then record the ID against the thread.
async function sendThreaded(env: Env, params: {
threadId: string;
to: string;
subject: string;
html: string;
// Pass the parent's Message-ID when this send is itself a reply.
inReplyTo?: string;
references?: string[];
}) {
const messageId = newMessageId("yourdomain.com");
const headers: Record<string, string> = {
"Message-ID": messageId,
Subject: params.subject,
To: params.to,
};
if (params.inReplyTo) {
headers["In-Reply-To"] = params.inReplyTo;
// References = inherited chain + the parent we are answering.
const chain = [...(params.references ?? []), params.inReplyTo];
headers["References"] = chain.join(" ");
}
await env.SEND.email({ headers, html: params.html }); // your sender of choice
// CRITICAL: store the exact Message-ID we just used.
await env.DB.prepare(
"INSERT INTO message_ids (message_id, thread_id, direction) VALUES (?, ?, 'outbound')",
)
.bind(messageId, params.threadId)
.run();
return messageId;
}
Two rules that people get wrong:
- Store the value exactly as you sent it, angle brackets and all. When the reply comes back you will compare strings; a stored value missing the brackets will never match the echoed one.
- Never reuse a
Message-ID. It must be unique per message, not per thread. Reusing one collapses unrelated messages and confuses every client in the chain.
What is the difference between In-Reply-To and References?
In-Reply-To holds the single Message-ID of the immediate parent, while References holds the ordered list of every Message-ID in the ancestry, root first and parent last. References is the more durable signal: if one intermediate message is missing from your records, the chain still contains an earlier ID you do recognize. The matching rule that follows from this is: walk References from the end (most recent) backward, and stop at the first ID you know.
When your own app sends a reply into an existing thread, you are responsible for propagating both headers so that the recipient's client keeps threading on their side too. That is what the In-Reply-To and References construction in the send function above does. Skip it and your replies look like new conversations in the customer's mailbox even if they thread correctly in yours.
Step 2: Parse the threading headers on inbound mail
In your email() handler, parse Message-ID, In-Reply-To, and References out of the raw MIME headers. The catch is that these headers are folded (wrapped across multiple indented lines) on long chains, and you must extract the angle-bracketed IDs rather than treating the raw value as one string.
// Unfold folded headers, then pull the named header's raw value.
function getHeader(rawHeaders: string, name: string): string | null {
const unfolded = rawHeaders.replace(/\r?\n[ \t]+/g, " ");
const re = new RegExp(`^${name}:\\s*(.*)$`, "im");
const m = unfolded.match(re);
return m ? m[1].trim() : null;
}
// Extract every <...> Message-ID from a header value, in order.
function extractMessageIds(value: string | null): string[] {
if (!value) return [];
const ids = value.match(/<[^<>@\s]+@[^<>\s]+>/g);
return ids ? ids : [];
}
interface ThreadingHeaders {
messageId: string | null; // this reply's own ID
inReplyTo: string | null; // immediate parent
references: string[]; // full chain, root-first
}
function parseThreadingHeaders(rawHeaders: string): ThreadingHeaders {
const messageIds = extractMessageIds(getHeader(rawHeaders, "Message-ID"));
const inReplyToIds = extractMessageIds(getHeader(rawHeaders, "In-Reply-To"));
return {
messageId: messageIds[0] ?? null,
inReplyTo: inReplyToIds[0] ?? null,
references: extractMessageIds(getHeader(rawHeaders, "References")),
};
}
extractMessageIds matters more than it looks. Real In-Reply-To headers sometimes carry trailing commentary like <id@host> (Alice's message of 18 Jun 2026), and References is frequently a space-or-newline-separated list. Pulling the angle-bracketed tokens with a regex sidesteps both. If you also need to parse the rest of the message (subject, body, attachments), see parsing raw MIME in JavaScript; here we only need the headers.
Step 3: Match the reply to a thread
Walk the inbound References newest-to-oldest, then fall back to In-Reply-To, and look each ID up in your stored outbound Message-ID values. The first hit identifies the thread. This ordering matters: the most recent reference is the most specific, and stopping at the first known ID keeps you on the deepest branch you actually sent.
async function findThread(
env: Env,
h: ThreadingHeaders,
): Promise<string | null> {
// Candidate IDs, most-recent first. References is root-first, so reverse it.
// In-Reply-To is the strongest single hint, so try it first.
const candidates = [
...(h.inReplyTo ? [h.inReplyTo] : []),
...[...h.references].reverse(),
];
if (candidates.length === 0) return null;
// One query, not a loop: ask for any stored ID that matches a candidate.
const placeholders = candidates.map(() => "?").join(",");
const row = await env.DB.prepare(
`SELECT message_id, thread_id FROM message_ids
WHERE message_id IN (${placeholders})`,
)
.bind(...candidates)
.all<{ message_id: string; thread_id: string }>();
if (row.results.length === 0) return null;
// Pick the match that appears earliest in our most-recent-first list.
const byId = new Map(row.results.map((r) => [r.message_id, r.thread_id]));
for (const id of candidates) {
const threadId = byId.get(id);
if (threadId) return threadId;
}
return null;
}
Note the single IN (...) query instead of looping a lookup per candidate ID. Replies on long threads can carry dozens of references; one query keeps the handler fast and within Worker CPU limits. The thread that owns the matched message is the thread the reply belongs to.
Step 4: Wire it into the inbound handler
Put the pieces together in the email() handler. Match first, fall back second, and always store the inbound reply's own Message-ID so a reply-to-the-reply threads too.
export default {
async email(message: ForwardableEmailMessage, env: Env): Promise<void> {
const raw = await streamToString(message.raw);
const headerBlock = raw.split(/\r?\n\r?\n/, 1)[0];
const h = parseThreadingHeaders(headerBlock);
let threadId = await findThread(env, h);
if (!threadId) {
threadId = await matchBySubjectAndParticipants(env, message, headerBlock);
}
if (!threadId) {
threadId = await createThread(env, message); // genuinely new conversation
}
// Record the reply's own Message-ID so future replies can match it.
if (h.messageId) {
await env.DB.prepare(
"INSERT OR IGNORE INTO message_ids (message_id, thread_id, direction) VALUES (?, ?, 'inbound')",
)
.bind(h.messageId, threadId)
.run();
}
await storeMessageInThread(env, threadId, message, raw);
},
};
If you have not yet designed the tables behind message_ids, threads, and the message store, the D1 email schema design guide covers the normalized layout and the indexes you need (a unique index on message_id is non-negotiable here).
What if a reply has no In-Reply-To or References header?
Fall back to matching a normalized subject against overlapping participants within a recent time window, and treat the result as a heuristic rather than a guarantee. Some clients strip threading headers, forwarded mail loses them, and a few mobile apps omit them entirely. Never merge threads on subject alone, because "Re: Question" collides constantly.
async function matchBySubjectAndParticipants(
env: Env,
message: ForwardableEmailMessage,
headerBlock: string,
): Promise<string | null> {
const subject = getHeader(headerBlock, "Subject") ?? "";
// Strip Re:/Fwd: prefixes (any language variant is messier; this covers most).
const normalized = subject
.replace(/^(\s*(re|fw|fwd)\s*:\s*)+/i, "")
.trim()
.toLowerCase();
if (!normalized) return null;
// Require BOTH a subject match AND a participant overlap, within 30 days.
const row = await env.DB.prepare(
`SELECT thread_id FROM threads
WHERE normalized_subject = ?
AND participants LIKE ?
AND last_activity > datetime('now', '-30 days')
ORDER BY last_activity DESC
LIMIT 1`,
)
.bind(normalized, `%${message.from}%`)
.first<{ thread_id: string }>();
return row?.thread_id ?? null;
}
This is the part that is genuinely a judgment call. Loosen it and you splice strangers into each other's threads; tighten it and legitimate replies start new conversations. The header path above is exact; this path is a safety net, and you should log when it fires so you can tune the window and the matching.
Common failure modes
Every reply starts a brand new thread
You are not setting a Message-ID you control on outbound mail, or you set it but never stored it. Without a stored ID there is nothing for the inbound In-Reply-To to match. Confirm step 1 actually writes a row.
Replies match the wrong (older) thread
You walked References root-first and stopped at the oldest ID instead of the newest. Reverse the chain and prefer In-Reply-To, so you land on the deepest branch.
Some replies thread, some do not, from the same customer
Their client folds the References header across lines and your parser reads only the first line. Unfold folded headers (\r?\n[ \t]+ to a space) before extracting IDs.
Two unrelated messages got merged
Your subject fallback matched on subject alone or with too wide a window. Require participant overlap and shorten the window; never merge on a normalized subject by itself.
Or skip the header plumbing: Tinbox threading
Everything above is correct and ownable, and for a single address it is maintainable. The friction is that threading is a cross-cutting concern: you have to remember the Message-ID on every send path, propagate References on every reply path, and keep the fallback honest, forever, across every feature that sends mail. Miss one send path and that feature's replies silently orphan.
Tinbox handles the whole loop on your own Cloudflare account. On send it generates a stable, domain-namespaced Message-ID, sets In-Reply-To and References when the message is itself a reply, and records the ID. On inbound mail it parses the threading headers, matches In-Reply-To and References against your stored IDs, falls back to a normalized-subject-plus-participant heuristic only when headers are absent, and writes the parsed reply into the correct thread in your D1 database.
npx tinbox init yourdomain.com
This scaffolds the inbound email() handler, provisions D1, R2, and Queues, and prints your DNS records. Sending a threaded reply is a method call, not a header-assembly exercise:
import { reply } from "tinbox/cf";
// `message` is an inbound message Tinbox already threaded for you.
await reply(env, {
to: message, // threads via the original Message-ID automatically
html: "<p>Thanks, we are on it.</p>",
});
// Tinbox sets Message-ID, In-Reply-To, and References, stores them, and
// keeps the conversation in one thread on both ends.
You never assemble a References chain, never debug a folded header, and never lose a reply because one send path forgot to set the ID. The same threaded conversation is what an assistant reads when you connect the MCP email server so Claude can summarize or answer in-thread.
Deploy this yourself: npx tinbox init yourdomain.com. Full docs for the inbound handler, threading, and the reply() helper are in the Tinbox documentation.
Frequently asked questions
How does email threading actually work?
Threading is driven by three headers. Every message has a unique Message-ID. A reply sets In-Reply-To to the Message-ID it answers, and References to the full chain of Message-IDs from the root down to the parent. To thread an inbound reply, you look up the IDs in its References (or In-Reply-To) header against the Message-IDs you recorded for messages you sent. A match means same thread.
What is the difference between In-Reply-To and References?
In-Reply-To holds the single Message-ID of the immediate parent message. References holds the ordered list of Message-IDs for the whole ancestry, root first, parent last. References is the more reliable signal because it survives a missing intermediate message; you should walk it from the end (most recent) backward and stop at the first ID you recognize.
How do I set a Message-ID when sending from a Worker?
Generate a unique, globally-namespaced value like <a-random-token@yourdomain.com> and set it as the Message-ID header on the outbound message before you hand it to your sender. Store that exact value in your database keyed to the thread, because the recipient's reply will echo it back in In-Reply-To and References.
What if a reply has no In-Reply-To or References header?
Some clients strip or omit them, especially forwarded mail and a few mobile apps. Fall back to matching on a normalized subject (strip Re:/Fwd: prefixes and whitespace) combined with overlapping participants and a recent time window. Treat this as a heuristic, not a guarantee, and never merge threads on subject alone.
Does Tinbox handle reply threading automatically?
Yes. Tinbox sets a stable Message-ID on every outbound message, records it, and on inbound mail matches In-Reply-To and References against your stored IDs before falling back to subject-and-participant heuristics. The parsed reply is written into the correct thread in your own D1 database with no header plumbing on your side.