Skip to content

StartReceive email in an agent

Receive email in an AI agent

Sending email from an agent is one API call. Receiving it is where agents break. The same event arrives twice, a reply lands in a new thread, a forged sender gets the agent to act, or the agent answers without knowing what was said before. This guide handles each of the four with a Shipmail mailbox, the TypeScript SDK and the message.received webhook.

Last updated

Before you start

  • A Shipmail mailbox on your domain for the agent, like agent@yourdomain.com. It is a normal mailbox: you can open it in the Shipmail app or a mail client and see everything the agent sees.
  • An API key from Developer, then API keys, limited to that mailbox. Give it messages:read to read mail, drafts:write for reply drafts, and messages:send only if the agent may send without review.
  • A webhook for message.received. Creating it needs webhooks:write on a key that is not limited to a mailbox, so do it once from the dashboard or with a separate setup key. That key also needs messages:read to turn on include_reply_text.
import { ShipmailClient } from "shipmail";

const shipmail = new ShipmailClient(process.env.SHIPMAIL_API_KEY ?? "");

const webhook = await shipmail.webhooks.create({
  url: "https://agent.example.com/webhooks/shipmail",
  events: ["message.received"],
  mailbox_ids: ["f47ac10b-58cc-4372-a567-0e02b2c3d479"],
  // Adds what the sender newly wrote. Needs a key with messages:read.
  include_reply_text: true,
  // Drops message.received when sender_authenticated is false.
  authenticated_senders_only: true,
  // Drops message.received from anyone else. Entries are addresses or exact domains.
  allowed_senders: ["jane@customer.com", "billing@supplier.com"],
});

// Shown once. Store it as SHIPMAIL_WEBHOOK_SECRET.
console.log(webhook.secret);

Duplicate deliveries

Shipmail waits 10 seconds for a 2xx response. A timeout or any other status counts as a failure, and Shipmail tries again after 1 minute, 5 minutes, 30 minutes and 4 hours. If your endpoint answered but too slowly, the agent gets the same email twice. After 5 failed deliveries in a row, Shipmail disables the endpoint and emails its owners.

Three rules keep this safe:

  1. Verify the signature before anything else. verifyWebhook from the SDK checks X-Shipmail-Signature and rejects a timestamp older than 5 minutes.
  2. Store the event under a unique key on its ID. The ID is event_id in the body and stays the same on every retry. If you set a Standard Webhooks secret on the webhook, the webhook-id header carries the same value.
  3. Answer at once, and let a worker run the model later.
CREATE TABLE shipmail_events (
  event_id     text PRIMARY KEY,
  payload      jsonb NOT NULL,
  received_at  timestamptz NOT NULL DEFAULT now(),
  processed_at timestamptz
);
import { Pool } from "pg";
import { verifyWebhook, type WebhookEvent } from "shipmail";

const db = new Pool({ connectionString: process.env.DATABASE_URL });

export async function POST(request: Request): Promise<Response> {
  const body = await request.text();

  let event: WebhookEvent;
  try {
    event = await verifyWebhook(body, request.headers, process.env.SHIPMAIL_WEBHOOK_SECRET ?? "");
  } catch {
    return new Response("Invalid signature", { status: 401 });
  }

  // The primary key drops a second delivery of the same event.
  await db.query(
    "INSERT INTO shipmail_events (event_id, payload) VALUES ($1, $2) ON CONFLICT (event_id) DO NOTHING",
    [event.event_id, body],
  );

  // Answer now. A worker reads rows where processed_at IS NULL.
  return new Response(null, { status: 204 });
}

The signature scheme and secret rotation are on webhook verification.

Spoofed senders

Anyone can write any address in a From header. An allowlist that only compares the From address checks a value the sender chose. Every message.received event carries authentication_results with spf, dkim and dmarc verdicts, and sender_authenticated, which is true when the sender passed DMARC, or when another Shipmail mailbox sent the message and Shipmail's own record of that send matches it.

The webhook above sets authenticated_senders_only, so Shipmail does not deliver mail from a sender that failed DMARC. It also sets allowed_senders, so Shipmail drops mail from every other sender too. Repeat both checks in your handler anyway, so the agent stays safe if someone changes these settings later.

const ALLOWED_SENDERS = new Set(["jane@customer.com", "billing@supplier.com"]);

type MessageReceived = {
  readonly mailbox_id: string;
  readonly email_id: string;
  readonly conversation_id: string | null;
  readonly from: { readonly address: string } | null;
  readonly reply_text?: string | null;
  readonly sender_authenticated?: boolean;
  readonly security?: { readonly status: "flagged" | "not_flagged" | "not_scanned" };
};

function isTrustedSender(data: MessageReceived): boolean {
  const sender = data.from?.address.toLowerCase();

  // True when DMARC tied the From address to the sending domain, or when Shipmail's own record
  // shows a Shipmail mailbox sent the message.
  // A delivery stored before the field existed does not have it, so missing counts as false.
  return data.sender_authenticated === true &&
    data.security?.status === "not_flagged" &&
    sender !== undefined && ALLOWED_SENDERS.has(sender);
}

When the check fails, leave the message for a person. Do not pass it to the model. A message that passes is still untrusted input: its body can contain text written to look like an instruction, so keep the agent's permissions small.

Memory

With include_reply_text, the webhook carries reply_text: what the sender newly wrote, without the quoted history, the "On ... wrote:" line or the signature. Give that to the model as the new message. It does not carry the earlier messages. Fetch the whole conversation by its ID, so the agent answers with what was already said, including replies a person sent from the same mailbox.

// The new message, from the webhook. Null when the sender wrote nothing new.
const newText = data.reply_text ?? null;

async function loadConversation(data: MessageReceived) {
  if (data.conversation_id === null) {
    // Rare: the message is not in a conversation yet. Use it on its own.
    return [await shipmail.mailboxes.getInboxMessage(data.mailbox_id, data.email_id)];
  }
  const thread = await shipmail.mailboxes.getInboxThread(data.mailbox_id, data.conversation_id);
  return thread.data;
}

Each message has its full text in body_values, reached through text_body[].part_id, and the same reply_text. The fields are described on mailbox inbox.

Threading

Every inbox message and every message.received event carries a conversation_id. Store that one. It is Shipmail's own ID and survives thread merges, while thread_id is deprecated. Reply through the conversation: Shipmail answers its latest inbound message, so the reply stays in the same thread. You pass the recipients. For a queued reply, target the original email ID so a retry cannot select a newer inbound message.

import { createHash } from "node:crypto";

const logicalKey = "reply-" + createHash("sha256")
  .update(JSON.stringify([data.mailbox_id, data.email_id]))
  .digest("hex");

// Persist the first generated replyText before this call. A retry reads that stored text.
if (data.from !== null) {
  await shipmail.mailboxes.replyToInboxMessage(
    data.mailbox_id,
    data.email_id,
    { to: [data.from.address], text: replyText, client_reference: logicalKey },
    // Same logical inbound message, same reference and key, even after an event replay.
    { idempotencyKey: logicalKey },
  );
}

To have a person approve the reply first, create a reply draft with drafts:write instead. Shipmail fills in To and Cc from the latest inbound message, and the draft waits in the same conversation. If newer mail arrives after the agent wrote it, sending the draft fails with 409. See reply drafts.

Idempotency keys on send

The same problem exists on the way out. A worker that times out and retries can send the same email twice. Send an Idempotency-Key header on every send and reply. For 24 hours, the same key with the same request returns the first response and sends nothing new. Save the first reply body before you send it. Build the key from the mailbox ID and the inbound email ID, so an event replay cannot create a second reply under a new key.

curl -X POST https://shipmail.to/api/v1/messages \
  -H "Authorization: Bearer sm_live_..." \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: invoice-2026-10-0042" \
  -d '{
    "from": "agent@yourdomain.com",
    "to": ["jane@customer.com"],
    "subject": "Your invoice",
    "text": "Hi Jane, your October invoice is ready."
  }'

Also set a stable client_reference on the reply. That reference outlives API-key rotation and the 24-hour response cache. Recover with messages.list({ client_reference: logicalKey }) and look at the result before you decide what to do. After an interrupted send, an empty result does not prove the original never left.

Details on idempotency.

A complete approval and recovery example

Download the runnable Bun example: the outbox workflow, its receiver and commands, and the setup and recovery instructions. Install shipmail and zod with Bun in the example directory. It uses a private SQLite database on one host.

  1. Verify the raw webhook and commit its receipt before returning 204.
  2. Deduplicate the event and the logical mailbox/message pair.
  3. Require an authenticated, allowed sender and a security status of not_flagged. Send other messages for human review.
  4. Freeze the proposed reply before any outbound request.
  5. Have a separate person inspect the original message, recipient and exact reply hash.
  6. Claim the approved row once, then send with its stored reference and key.
  7. Read positive send evidence after an interruption. Keep unknown outcomes for review.

A webhook replay keeps its original security result. Fetch the message before processing it to read its current review state. A not_flagged result does not prove that content is safe. The scanner checks patterns and attachment names, not attachment contents. Treat every email field as untrusted input.

import { ReplyOutbox } from "./workflow";

const outbox = new ReplyOutbox("/private/agent/outbox.sqlite");

// A worker freezes its proposed text. Repeating this with different text fails.
const draft = outbox.saveDraft(jobId, firstGeneratedReply);

// A separate human process inspects draft_json and approves this exact draft_hash.
// Keep this process and the sending key outside the model's tools.
outbox.approve(jobId, reviewedHash, "operator-name");

// A sender claims the approved row atomically. Only one worker can dispatch it.
await outbox.send(jobId, sendingClient);

// A timeout never returns the row to the send queue. Read the provider's evidence.
await outbox.reconcile(jobId, readOnlyClient);

The reference tests cover duplicate events, exact approval, concurrent sending, interrupted processes and recovery after key rotation. They use synthetic responses and send no email. For several application hosts, use your database's durable outbox and transactional claims instead of sharing a SQLite file.

Keep a person in the loop

The agent works in a real mailbox on your domain, so your team sees the same conversations it does. They can read what it sent, answer a thread themselves, or send a draft it left. Everything the agent does shows up in that mailbox.

Frequently asked questions

Which ID do I dedupe on?

The event ID. It is event_id in the body and the X-Shipmail-Event-Id header. If you set a Standard Webhooks secret on the webhook, the webhook-id header carries the same value. It stays the same on every retry and replay of that event.

Does message.received include the email body?

Not the full body. With include_reply_text on the webhook, it carries reply_text: what the sender newly wrote, without quoted history or the signature. Every delivery also carries the SPF, DKIM and DMARC results and sender_authenticated. Fetch the message or the conversation with the API for the full body, the HTML and the attachments.

Should I store thread_id or conversation_id?

Store conversation_id. It is Shipmail's own ID and survives thread merges. thread_id is deprecated, and every inbox thread endpoint accepts a conversation_id in its place.

Can a person see what the agent did?

Yes. The agent works in a normal Shipmail mailbox on your domain. Its replies and drafts show in the same conversation in the Shipmail app and in any mail client connected to that mailbox.

How long does an idempotency key last?

The response cache lasts 24 hours and belongs to the API key that made the request. To find a reply after a key rotation or after those 24 hours, set a stable client_reference on it. Save the first reply body, reference and key before you send. If you do not know whether a send went out, look it up by its client_reference instead of sending again with a new key.