AgentMailr's wait_for_email endpoint is perfect for synchronous flows where an agent blocks until it receives a specific email. But many production architectures are event-driven: a serverless function, a queue consumer, or an automation platform like n8n or Zapier needs to react to inbound emails without maintaining a persistent HTTP connection.

Registering a Webhook

// Register a webhook for all inbound emails to an inbox
const webhook = await client.webhooks.create({
  url: "https://your-worker.example.com/email-received",
  events: ["email.received"],
  inbox_id: "inb_abc123", // optional — omit for all inboxes
  secret: "wh_secret_for_hmac_verification",
});

When an email arrives, AgentMailr makes a POST to your endpoint within seconds with a signed payload:

{
  "event": "email.received",
  "inbox_id": "inb_abc123",
  "email": {
    "id": "eml_xyz789",
    "from": "support@stripe.com",
    "subject": "Your payout has been processed",
    "otp_code": null,
    "verification_links": [],
    "body_text": "Your payout of $1,234.56 was sent...",
    "category": "transactional"
  }
}

Verifying Webhook Signatures

Always verify the HMAC-SHA256 signature before processing:

import crypto from "crypto";

function verifyWebhook(payload: string, signature: string, secret: string): boolean {
  const expected = crypto
    .createHmac("sha256", secret)
    .update(payload)
    .digest("hex");
  return crypto.timingSafeEqual(
    Buffer.from(signature),
    Buffer.from(expected)
  );
}

Triggering Agent Workflows

Once your endpoint receives and verifies the webhook, you can trigger any downstream workflow:

  • n8n / Make / Zapier: Use a webhook trigger node — AgentMailr POSTs to it directly
  • AWS Lambda / Cloudflare Workers: Deploy a lightweight handler that enqueues work to SQS or a Durable Object
  • LangChain / CrewAI agents: Spawn an agent with the email context as the initial prompt

Webhook vs Long-Poll: When to Use Which

PatternBest For
Long-poll (wait_for_email)Synchronous agent flows, Playwright automation, sequential task chains
WebhooksEvent-driven pipelines, serverless functions, automation platforms, fan-out to multiple systems

Most production systems use both: long-poll for inline agent verification steps, webhooks for async notification pipelines. AgentMailr supports both patterns natively.