Route Incoming Email to the Right Customer Agent

8 min read

Route incoming email from one Robotomail account to the right customer and agent: verify, map the mailbox, dedupe durably and resume the right run.

John Joubert

John Joubert

Founder, Robotomail

Route Incoming Email to the Right Customer Agent
Table of contents

To route incoming email to the right customer and agent, treat the mailbox ID in a verified webhook as the only routing key. Look it up in your own mapping table, commit a dedupe record and a durable job in one transaction, and only then acknowledge. A worker then resumes the agent run tied to that mailbox and thread. Parsing the webhook is the easy first step. The hard part is correctness when replies from different customers arrive interleaved, retried and out of order.

This guide uses a fictional platform, RelayDesk, which runs enquiry-handling agents for businesses. Two fictional customers, Cedar and Harbor, each have a qualification agent with its own mailbox. RelayDesk holds one Robotomail account. Robotomail supplies the mailboxes, webhooks and message storage. RelayDesk owns everything else: the customer database, the model, the scheduler, billing and permissions. All names, IDs and example.com addresses here are illustrative. Every database, queue and router function below is RelayDesk application code, not a Robotomail feature.

If you need a refresher on reading the payload itself, start with parsing an inbound email webhook. This post assumes you can already do that.

Why one parsed webhook is not enough

Here is a plausible ten-second window at RelayDesk:

Order Delivery Mailbox Thread What goes wrong if you are naive
1 Cedar prospect replies Cedar's mailbox T1 Nothing yet
2 Harbor prospect replies Harbor's mailbox T7 Routing by From domain could pick the wrong customer if the sender emails both
3 Delivery 1 retried after a slow ack Cedar's mailbox T1 Cedar's agent runs twice
4 Cedar prospect sends a correction Cedar's mailbox T1 Two workers race on T1 and send contradicting replies

Each event parses fine. The bugs come from routing, duplicates and concurrency. The design below handles each one explicitly.

Establish the trusted mapping before mail arrives

RelayDesk's provisioning service is trusted platform code. When it creates a mailbox for an agent, it writes one row:

customer_id | agent_id | mailbox_id | mailbox_address | credential_secret_ref | lifecycle_state

There is a unique constraint on (customer_id, agent_id) and on mailbox_id. Runtime workers never get the account key. They receive only the scoped credential referenced by credential_secret_ref.

Two rules matter here:

  • Robotomail account ownership does not distinguish your customers. Every mailbox belongs to RelayDesk's account. Your table is the only thing that says "this mailbox is Cedar's."
  • Never accept a browser-supplied mailbox ID as proof of ownership. If a dashboard lets Cedar view its inbox, resolve the mailbox from Cedar's authenticated session through your table, not from a query parameter.

Then register a webhook endpoint. You can register one account-wide, which requires a full-access API key, or register one per mailbox by passing that mailbox's mailboxId. The request shape and options are in the webhooks documentation. The creation response returns the signing secret once. Store it in your secret manager immediately and keep it out of logs and test fixtures.

Configure the receiver with a known secret for a known endpoint. If you run several registrations, give each its own path and its own configured secret. Never pick a secret or a tenant from a field inside the unverified payload.

Verify the raw bytes, then parse

Robotomail signs each delivery with an X-Robotomail-Signature header: a hex HMAC-SHA256 of the raw request body, keyed with the webhook secret. Compute it over the exact bytes you received, before any JSON parsing or re-serialization. Compare in constant time, after checking lengths.

The signature has no timestamp component. A valid signature proves the body came from Robotomail with your secret. It does not prove the request is fresh. Replay protection comes from the dedupe step below, not from verification.

Route incoming email by mailbox ID only

After verification:

  1. Require event == "message.received". Acknowledge and ignore other events you have not explicitly opted to handle.
  2. Validate that data.mailbox_id and data.message_id are present strings.
  3. Look up data.mailbox_id in the active mapping.

Do not route by from, subject, a customer ID in the body, or a guess based on the address local part. A prospect can email both Cedar and Harbor. A subject can say anything.

If the mailbox is unknown or offboarded, write a quarantine record with minimal metadata (delivery ID, mailbox ID, message ID, received time) for reconciliation. Do not fall back to a default customer's agent. A misrouted enquiry is a data leak between tenants.

Commit dedupe and the job together, then acknowledge

Robotomail delivers webhooks at least once (see delivery semantics), so retries are normal. RelayDesk uses two dedupe keys:

  • X-Robotomail-Delivery-Id is stable across retries of the same delivery. It is a header, not part of the signed body.
  • (mailbox_id, event, data.message_id) covers the case where two webhook registrations, say an account-wide one and a mailbox-scoped one, each produce a separate delivery for the same message.

Both inserts and the outbox job go into one application transaction. Acknowledge only after commit. If storage fails, return a retryable error so Robotomail tries again.

Here is the receiver. The db module is RelayDesk pseudocode.

// RelayDesk application code. Not a Robotomail feature.
import express from "express";
import crypto from "node:crypto";
import { db, UniqueViolation } from "./relaydesk-db"; // RelayDesk pseudocode

const app = express();
// One configured secret for this endpoint. Never chosen from the payload.
const WEBHOOK_SECRET = process.env.ROBOTOMAIL_WEBHOOK_SECRET!;

function signatureOk(raw: Buffer, header: string | undefined): boolean {
  if (!header) return false;
  const expected = crypto.createHmac("sha256", WEBHOOK_SECRET).update(raw).digest("hex");
  const a = Buffer.from(header, "utf8");
  const b = Buffer.from(expected, "utf8");
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}

const DUPLICATE_CONSTRAINTS = new Set(["webhook_deliveries_pkey", "inbound_work_key"]);

app.post("/inbound", express.raw({ type: "application/json" }), async (req, res) => {
  const raw = req.body as Buffer;

  // 1. Verify exact bytes before parsing anything.
  if (!signatureOk(raw, req.header("X-Robotomail-Signature"))) return res.sendStatus(401);

  const evt = JSON.parse(raw.toString("utf8"));
  if (evt.event !== "message.received") return res.sendStatus(204);

  const d = evt.data ?? {};
  const deliveryId = req.header("X-Robotomail-Delivery-Id");

  try {
    await db.transaction(async (tx) => {
      if (!deliveryId || typeof d.mailbox_id !== "string" || typeof d.message_id !== "string") {
        await tx.quarantine({ deliveryId, mailboxId: d.mailbox_id, reason: "malformed" });
        return;
      }

      // 2. Dedupe keys. Each insert has its own named unique constraint.
      await tx.insertDelivery(deliveryId);                            // webhook_deliveries_pkey
      await tx.insertWorkKey(d.mailbox_id, evt.event, d.message_id);  // inbound_work_key

      // 3. Route by mailbox_id only. Shared row lock guards against an offboarding race.
      const route = await tx.activeMailboxRoute(d.mailbox_id, { lock: "share" });
      if (!route) {
        await tx.quarantine({ deliveryId, mailboxId: d.mailbox_id, messageId: d.message_id, reason: "unknown_or_offboarded" });
        return;
      }

      // 4. Quota-withheld events are not enquiries yet.
      if (d.over_limit === true) {
        await tx.reconcileLater({ ...route, storedMessageId: d.message_id, receivedAt: d.received_at });
        return;
      }

      // 5. Durable job for the worker.
      await tx.enqueueOutbox({
        customerId: route.customer_id,
        agentId: route.agent_id,
        mailboxId: d.mailbox_id,
        storedMessageId: d.message_id,
        threadId: d.thread_id,
      });
    });
  } catch (err) {
    // Only the intended dedupe conflicts count as "already handled".
    if (err instanceof UniqueViolation && DUPLICATE_CONSTRAINTS.has(err.constraint)) {
      return res.sendStatus(200);
    }
    return res.sendStatus(503); // retryable: nothing committed
  }

  return res.sendStatus(200); // acknowledge only after commit
});

Note the catch block. Catching every unique violation as success would hide real bugs, such as a broken outbox schema, and silently drop mail. The field names in data follow the event payload reference.

Resume the right agent run

The worker claims outbox jobs and does the slow work. Four rules:

  1. Serialize per conversation. Hold a lock on (mailbox_id, thread_id) so Cedar's correction in step 4 waits for the first run on T1 to finish. Harbor's T7 proceeds in parallel.
  2. Fetch with the scoped key. Load the stored message, and the thread if the agent needs history, through the Messages API using that agent's credential. The response is camelCase: message.id, message.mailboxId, message.threadId, message.messageId, message.fromAddress, message.bodyText.
  3. Verify context. Confirm the returned mailboxId and threadId match the job. On mismatch, quarantine.
  4. Treat email as untrusted input. Body text is data for the model, never an instruction to change permissions, recipients or tools.
// RelayDesk worker pseudocode. Locking, runs, agents and sends are application-owned.
// rm.getMessage / rm.sendMessage are RelayDesk's thin HTTP wrapper, not a shipped SDK.
async function handleJob(job) {
  await withConversationLock(job.mailboxId, job.threadId, async () => {
    const route = await db.activeMailboxRoute(job.mailboxId);
    if (!route) return quarantine(job, "offboarded_before_processing");

    const key = await secrets.read(route.credential_secret_ref); // scoped to this mailbox
    const { message } = await rm.getMessage(key, job.mailboxId, job.storedMessageId);

    if (message.mailboxId !== job.mailboxId || message.threadId !== job.threadId) {
      return quarantine(job, "context_mismatch");
    }
    if (!message.messageId) return humanReview(job, "missing_rfc_message_id");

    const run = await runs.findOrCreate(job.customerId, job.agentId, job.mailboxId, job.threadId);
    const decision = await agents.resume(run, { untrustedEmail: message });
    if (decision.kind !== "reply") return;

    const intent = await sends.recordIntent(run.id, message.id, decision); // before sending
    try {
      const result = await rm.sendMessage(key, job.mailboxId, {
        to: [message.fromAddress],
        subject: `Re: ${message.subject}`,
        bodyText: decision.text,
        inReplyTo

Give your AI agent a real email address

Create a mailbox, connect your agent and test a conversation. Send, receive and retrieve the thread through one API.

Related posts