Receive email replies in your SaaS app: a Node.js guide
Receive replies as application comments with a signed webhook, a durable SQLite record, known-thread matching and checks on who sent the message.
By Arin Prajapati, founder, 11 min read
On this page (7)
To receive email replies in your SaaS app, send from a receiving inbox, save the outbound thread against an application conversation, and subscribe to a signed message.received webhook. Fetch the stored message, match it to that conversation, check the sender, and commit the reply before acknowledging the event. This guide implements that path in Node.js with SQLite, including duplicate handling and a review queue for uncertain mail.
Checked and exercised November 26, 2026. The example uses the current sending, messages and webhooks contracts. For provider selection, start with the inbound email API comparison.
Choose a reply address pattern
Swipe sideways to see every column.
| Pattern | How it routes | What to watch |
|---|---|---|
| One shared inbox | Match the received thread to the conversation saved at send time | A new email with no threading headers needs review or a separate ticket |
| Per-conversation Reply-To | Use reply+<random-token>@replies.example.com and map the envelope recipient | Provision delivery for the domain; tokens must be unpredictable and scoped |
| One inbox per customer or agent | Map inbox_id, then thread_id | Check plan inbox limits; inbox identity alone does not identify a conversation |
Standard email replies reference earlier messages with In-Reply-To and References [1]. Runearc groups a received message with a matching Message-ID in the same inbox; otherwise it creates a new thread. Save the thread_id returned from sending, rather than matching the subject or trusting a ticket number typed into an email.
If you need routing even when a client loses the headers, use reply_to on the send request and resolve a random per-conversation token from delivered_to on the received message. Runearc keeps +tags in those envelope recipients. A plus address still needs an inbox or catch-all configuration that accepts it; writing an address into Reply-To does not create a mailbox. Do not put an enumerable internal database id in a public reply address.
For an established company mail domain, use a receiving subdomain so application mail does not replace employees' MX records. The domains guide covers verification, and stored inboxes explain the mail model.
Send and save the thread
The program below has two commands: send creates a ticket notification from an existing inbox, while serve receives events. The send command calls POST /v1/inboxes/{id}/messages, saves the returned thread, inbox and expected participant, and uses a stable Idempotency-Key. Its recipient is chosen by your trusted backend, not by an unauthenticated browser form.
Use a server-side API key with the scope needed for the inbox. Export RUNEARC_API_KEY, RUNEARC_INBOX_ID, RUNEARC_WEBHOOK_SECRET and, optionally, REPLIES_DB; keep them out of client bundles and source control. Use Node.js 24 or later for the built-in node:sqlite module.
Create an inbox first, then create a webhook with your public HTTPS URL ending in /hooks/runearc, event_types: ["message.received"], and that inbox_id. The response's whsec_ secret is shown once. The complete webhook creation and verification contract includes the request shape.
Receive and store replies
Save this as replies.mjs. It listens only on loopback: terminate HTTPS at your application gateway and forward this one route to it. Keep the SQLite file on durable storage. The replies table is the example's application comment store; show only accepted rows to participants and expose the other dispositions to an authorized reviewer.
import crypto from "node:crypto";
import http from "node:http";
import { DatabaseSync } from "node:sqlite";
const API = process.env.RUNEARC_API_URL ?? "https://api.runearc.com/v1";
const db = new DatabaseSync(process.env.REPLIES_DB ?? "replies.sqlite");
db.exec(`
PRAGMA journal_mode=WAL;
CREATE TABLE IF NOT EXISTS conversations (
id TEXT PRIMARY KEY, thread_id TEXT UNIQUE NOT NULL,
inbox_id TEXT NOT NULL, participant TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS receipts (
event_id TEXT PRIMARY KEY, message_id TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS replies (
message_id TEXT PRIMARY KEY, conversation_id TEXT,
disposition TEXT NOT NULL, original_text TEXT, preview TEXT,
message_json TEXT NOT NULL
);
`);
async function api(path, init = {}, raw = false) {
const r = await fetch(`${API}${path}`, {
...init, signal: AbortSignal.timeout(3000),
headers: { Authorization: `Bearer ${process.env.RUNEARC_API_KEY}`,
"Content-Type": "application/json", ...init.headers },
});
if (!r.ok) throw new Error(`Runearc HTTP ${r.status}`);
return raw ? r.text() : r.json();
}
export function verify(secret, headers, body) {
const id = headers["webhook-id"];
const ts = headers["webhook-timestamp"];
const sigs = headers["webhook-signature"];
if (typeof id !== "string" || typeof ts !== "string" ||
typeof sigs !== "string" || !/^\d+$/.test(ts)) throw Error("headers");
const seconds = Number(ts);
if (!Number.isSafeInteger(seconds) ||
Math.abs(Date.now() / 1000 - seconds) > 300) throw Error("stale");
if (!secret?.startsWith("whsec_")) throw Error("secret");
const expected = crypto.createHmac("sha256", Buffer.from(secret.slice(6), "base64"))
.update(`${id}.${ts}.${body}`).digest();
const valid = sigs.split(" ").some((s) => {
const [version, signature] = s.split(",");
const given = Buffer.from(signature ?? "", "base64");
return version === "v1" && given.length === expected.length &&
crypto.timingSafeEqual(given, expected);
});
if (!valid) throw Error("signature");
const event = JSON.parse(body);
if (event.id !== id) throw Error("event id");
return event;
}
// A preview only. Preserve original_text for review and better parsing later.
export function preview(text) {
return (text ?? "").split(/\r?\n/).slice(0, 200)
.join("\n").split(/\n(?:On .+wrote:|> ?|-- ?\n)/)[0].trim();
}
function rawHeaders(raw) {
return raw.split(/\r?\n\r?\n/, 1)[0].replace(/\r?\n[ \t]+/g, " ");
}
export function disposition(message, conversation, raw) {
const h = rawHeaders(raw);
const automated = /^Auto-Submitted:\s*(?!no\s*$)\S/im.test(h) ||
/^Return-Path:\s*<>/im.test(h) ||
/^Content-Type:\s*multipart\/report\b/im.test(h);
if (automated) return "automated";
if (!conversation || message.inbox_id !== conversation.inbox_id ||
message.from?.toLowerCase() !== conversation.participant ||
message.auth_results?.dmarc !== "pass" || message.spam)
return "review";
return "accepted";
}
export async function receive(event) {
if (event.type !== "message.received") return;
if (db.prepare("SELECT 1 FROM receipts WHERE event_id = ?").get(event.id)) return;
const id = event.data?.message_id;
if (typeof id !== "string" || !/^msg_[a-z0-9]+$/.test(id)) throw Error("message id");
const m = await api(`/messages/${id}`);
if (m.direction !== "in") throw Error("direction");
const c = db.prepare("SELECT * FROM conversations WHERE thread_id = ?").get(m.thread_id);
const raw = await api(`/messages/${id}/raw`, {}, true);
const state = disposition(m, c, raw);
// Event receipt and application record become durable together, before 204.
db.exec("BEGIN IMMEDIATE");
try {
db.prepare("INSERT OR IGNORE INTO receipts VALUES (?, ?)").run(event.id, id);
db.prepare("INSERT OR IGNORE INTO replies VALUES (?, ?, ?, ?, ?, ?)")
.run(id, c?.id ?? null, state, m.text ?? null, preview(m.text), JSON.stringify(m));
db.exec("COMMIT");
} catch (error) { db.exec("ROLLBACK"); throw error; }
}
async function send(id, participant) {
if (!id || !participant || !process.env.RUNEARC_INBOX_ID) throw Error("send arguments");
if (db.prepare("SELECT 1 FROM conversations WHERE id = ?").get(id)) return;
const inbox = process.env.RUNEARC_INBOX_ID;
const m = await api(`/inboxes/${encodeURIComponent(inbox)}/messages`, {
method: "POST", headers: { "Idempotency-Key": `ticket:${id}` },
body: JSON.stringify({ to: participant, subject: `Ticket ${id}`,
text: "Reply to this email to add a comment to your ticket." }),
});
db.prepare("INSERT INTO conversations VALUES (?, ?, ?, ?)")
.run(id, m.thread_id, inbox, participant.toLowerCase());
console.log("Conversation saved; replies can now be matched.");
}
if (process.argv[2] === "send") {
await send(process.argv[3], process.argv[4]);
} else if (process.argv[2] === "serve") {
http.createServer(async (req, res) => {
if (req.method !== "POST" || req.url !== "/hooks/runearc") {
res.writeHead(404).end(); return;
}
const chunks = [];
try {
let bytes = 0;
for await (const chunk of req) {
bytes += chunk.length;
if (bytes > 65536) { res.writeHead(413).end(); return; }
chunks.push(chunk);
}
const body = Buffer.concat(chunks).toString("utf8");
let event;
try { event = verify(process.env.RUNEARC_WEBHOOK_SECRET, req.headers, body); }
catch { res.writeHead(401).end(); return; }
await receive(event);
res.writeHead(204).end();
} catch { res.writeHead(503).end(); }
}).listen(Number(process.env.PORT ?? 3000), "127.0.0.1");
}The three-second timeout applies to each API read. A failed read or database write returns 503, allowing a provider retry. A duplicate webhook-id short-circuits after the first commit; a unique message_id also prevents a second webhook subscription or replay from creating the same application reply twice. The receipt and reply insert happen in one SQLite transaction.
Signature verification uses the raw body bytes converted to UTF-8 once, validates a numeric timestamp within five minutes, and compares the HMAC in constant time. It follows the Standard Webhooks signed string id.timestamp.body [3]. Rejecting old attempts does not reject legitimate retries: Runearc signs each attempt with its current timestamp and keeps the event id stable.
Sender trust and automated mail
The handler reads the full message from Runearc rather than trusting sender fields supplied in an arbitrary HTTP request. An accepted reply requires a known thread, the same inbox, the stored participant's address, a dmarc: "pass" verdict, and no spam flag. Unchecked or failing authentication is retained as review, rather than silently discarded or attached as an authorized comment.
These checks reduce misrouting; they do not establish a person's identity. DMARC verifies domain alignment. A compromised account at the expected address can still send mail, and forwarded messages or mailing lists may fail a strict policy. Keep email-originated comments separate from authorization to change billing, export private data or reset credentials. Require a signed-in action for those operations.
The raw message is fetched to inspect Auto-Submitted, a null return path and delivery-status MIME reports. RFC 3834 describes automated-response handling [2]. The sample labels such messages automated and sends no automatic response, which avoids generating a reply loop. The simple checks are conservative and do not classify every vendor's vacation or bounce format. For outbound failures, subscribe separately to message.bounced and related delivery events instead of treating a bounce as a customer comment.
Runearc does not expose a dedicated quoted-reply or signature-stripping field. preview() removes a few common English plain-text markers and a -- signature boundary, then stops. It deliberately stores original_text and the full message object too. It can trim legitimate inline replies, miss localized markers, and does not parse HTML. Render the preview as escaped text; sanitize HTML separately, and scan attachments before offering them to users.
Run and verify it
After setting the environment variables, run node replies.mjs send ticket-42 customer@example.com from your trusted backend environment, then node replies.mjs serve. Reply from that customer's mailbox to the notification. Query replies.sqlite for the result, then replay the same webhook and confirm the row count remains one.
On November 26 we ran this program against an isolated local Runearc API, a throwaway PostgreSQL database and the real SMTP receiver. The outbound send returned a stored message; real SMTP replies joined its thread. The handler rejected forged and stale signatures with 401, kept an unchecked sender for review, accepted a matching participant under a seeded passing verdict, deduplicated repeated events and message ids, trimmed a quoted preview, and classified an automatic reply and a different sender separately. The Deno example in the Lovable integration also exercised the same local sending API.
That run did not test production delivery or live DNS authentication. SMTP authentication checks were disabled locally, and passing DMARC verdicts were seeded only in the throwaway test database to exercise the policy branches. The outbound relay was disabled, so nothing was sent to external recipients. Both the processes and database were removed after verification. Hosted deployment, a real customer's mailbox and a live DMARC pass remain deployment checks.
What to add before production
Keep a durable outbox for outbound notifications. This compact example saves the conversation after the API send: a crash between those steps leaves a mapping to reconcile. The stable send key makes retries safe within Runearc's documented 24-hour idempotency window, not forever. Reconcile unresolved sends before that window expires instead of blindly resending days later. Do not change the body when retrying the same key.
The webhook handler commits a short operation synchronously. If your app needs AI processing, downloads, indexing or other slow work, commit a durable queue item first and let a worker process it with its own idempotency key. Acknowledge only after the queue write. Add an event/message reconciliation job for exhausted retries and operational monitoring of the review queue.
For multiple tenants, store and enforce the tenant id at every conversation lookup and UI query. This example is a single trusted backend and one workspace. Add retention rules, encrypted backups, attachment scanning and application-level quotas before accepting arbitrary public mail. Keep the inbox key and webhook secret separate and rotate either without exposing them to a client.
Free Runearc workspaces send 3,000 recipients/month, carry a footer for external recipients, and start with a 100-recipient daily limit for the first seven days. A verified domain removes the sending sandbox; receiving does not consume the sending allowance. Those limits apply to outbound notifications and replies, not to your application's database capacity.
Questions
Can I put a conversation id in Reply-To?
Yes, but use an unpredictable token rather than an enumerable ticket id, and arrange delivery for that address. Treat the token as routing information, bind it to the intended participant and tenant, and do not let possession alone authorize sensitive actions.
Does Runearc strip quoted replies?
It exposes text and HTML bodies, not a dedicated stripped-reply field. The example creates a limited English plain-text preview and keeps the original. It is not a complete quote or signature parser.
Does a signed webhook prove who wrote the email?
No. It proves the event was signed by the provider. DMARC authenticates an aligned sending domain, not the individual person. The example also requires a known thread and expected sender, and keeps uncertain messages for review.
Why not return 200 before writing to the database?
A process can fail after acknowledging an event. The example commits the receipt and reply together before responding. For expensive processing, first write a durable job and then acknowledge; an in-memory background promise is not a durable queue.
Sources, read on November 26, 2026
- [1]RFC 5322, message identification fields: www.rfc-editor.org/rfc/rfc5322#section-3.6.4
- [2]RFC 3834, automatic responses: www.rfc-editor.org/rfc/rfc3834
- [3]Standard Webhooks: www.standardwebhooks.com/
If something here is out of date or wrong, email hello@runearc.com and we will fix it.

Arin Prajapati, founder of RunearcA software engineer in Mumbai who builds Runearc's mail servers, API and site. More about Arin and why he built Runearc.
Read next
- Best inbound email APIs in 2026: receive and parse emailEight ways to receive email in code, read from each provider's own docs on November 26, 2026: how mail reaches you, whether it is kept and queryable later, what the parsed payload holds, retries, signatures, IMAP and the free tier.
- An email inbox for your AI agentAn agent that signs up for things needs an address that receives mail, and a way to get the code out of it without polling. Here is the whole flow in three steps.
- Webhooks and eventsSigned events at your URL, a WebSocket stream, retries and replay.
Put Runearc to work
Get inboxes, sending, your own domains and MCP in one workspace. The free plan includes 3 inboxes, 3,000 emails a month and 3 custom domains, with no card.