Email OTP API: Receive Verification Codes Programmatically

8 min read

Use an email OTP API to receive verification codes and magic links: per-task addresses, webhook waits with timeouts, safe parsing, and expiry handling.

John Joubert

John Joubert

Founder, Robotomail

Email OTP API: Receive Verification Codes Programmatically
Table of contents

An email OTP API lets your code receive a one-time code or magic link in a real inbox and read it programmatically, without a human copying it from Gmail. The pattern has four steps. Give each task its own address, wait for the inbound message with a hard timeout, extract the expected code or link, and treat expiry as a normal outcome rather than an error.

This guide is about receiving codes for apps and accounts you control: your own product's signup flow in end-to-end tests, internal tools, or services where your agent is the legitimate account holder. It is not about sending OTPs. That job belongs to your auth provider or transactional mailer.

How an email OTP API flow works

The sequence looks like this:

  1. Your agent or test runner creates, or picks, a mailbox for the task.
  2. It submits that address to the app's signup or login form.
  3. The app emails a code or link to that address.
  4. Your mail provider receives the message and pushes it to your webhook as JSON.
  5. Your code matches the message to the waiting task, parses out the code, and continues.

The hard parts sit in steps 1, 4 and 5. If tasks share an inbox, they read each other's codes. If the wait has no deadline, it hangs. If the parser is too loose, it grabs the wrong number. We run mail infrastructure, and almost every flaky OTP flow we see traces back to one of those three.

Step 1: Give each task its own address

Correlation is easiest when the address itself is the correlation key. Create a mailbox per task, per test run, or per agent, so any message that arrives at qa-run-8f3a@robotomail.co can only belong to one waiter.

With the CLI:

npx @robotomail/cli mailbox create qa-run-8f3a

Or with the API:

curl -X POST https://api.robotomail.com/v1/mailboxes \
  -H "Authorization: Bearer rm_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{"address": "qa-run-8f3a"}'

Leave out domainId and the mailbox lives on the platform domain. If the app you are testing only allows addresses on your own domain, or treats shared domains differently, add a custom domain and pass that domain's UUID as domainId. For bulk or on-demand provisioning, see our guide to creating email accounts programmatically via API.

If per-task mailboxes don't suit your setup, you can reuse one mailbox. In that case, correlate on something the app echoes back, such as a username in the subject line, and pair it with a strict "received after I triggered it" check. Per-task addresses are simpler and harder to get wrong.

Step 2: Wait for the message with a timeout

Inbound mail reaches you as a webhook POST with this shape:

{
  "event": "message.received",
  "data": {
    "message_id": "...",
    "mailbox_id": "...",
    "mailbox_address": "qa-run-8f3a@robotomail.co",
    "from": "no-reply@yourapp.example",
    "subject": "Your verification code",
    "body_text": "Your code is 482913. It expires in 10 minutes.",
    "thread_id": "...",
    "received_at": "2026-04-17T10:00:00.000Z"
  }
}

Register the webhook as its own resource, then keep a map of pending waiters keyed by mailbox address. The handler resolves a waiter, and the waiter rejects if the deadline passes first.

type Inbound = {
  mailbox_address: string;
  from: string;
  subject: string;
  body_text: string;
  received_at: string;
};

const waiters = new Map<string, (msg: Inbound) => void>();

export function waitForEmail(address: string, timeoutMs = 120_000): Promise<Inbound> {
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => {
      waiters.delete(address);
      reject(new Error(`No email for ${address} within ${timeoutMs}ms`));
    }, timeoutMs);

    waiters.set(address, (msg) => {
      clearTimeout(timer);
      waiters.delete(address);
      resolve(msg);
    });
  });
}

// Webhook route handler (Express-style)
export function onWebhook(body: { event: string; data: Inbound }) {
  if (body.event !== "message.received") return;
  const resolver = waiters.get(body.data.mailbox_address.toLowerCase());
  if (resolver) resolver(body.data);
}

Register the waiter before you submit the form. If you do it the other way round, a fast mailer can deliver before anything is listening. Normalize addresses to lowercase on both sides. In production, verify the webhook signature before trusting the payload. The docs cover the verification details.

If your runner lives somewhere that can't accept inbound HTTP, such as a laptop or a locked-down CI job, use a streaming connection instead. Robotomail exposes account events over SSE, described in the events reference. The waiter logic stays the same, only the transport changes. You can also fetch messages for a mailbox after the fact, as covered in the messages API docs, which is useful as a fallback check when a wait times out.

Choose timeouts deliberately. Most transactional mail arrives within seconds, but greylisting and provider queues can stretch that. Somewhere between one and three minutes is a reasonable ceiling for tests. Past that, fail loudly instead of retrying silently.

Write the parser around what you expect, not around "any number in the email." Footers contain years, phone numbers and order IDs that a naive regex will happily match.

export function extractCode(msg: Inbound, expectedFrom: string): string {
  if (!msg.from.toLowerCase().endsWith(expectedFrom)) {
    throw new Error(`Unexpected sender: ${msg.from}`);
  }
  // Anchor on the phrase your app actually uses.
  const m = msg.body_text.match(/code is[:\s]+(\d{6})\b/i);
  if (!m) throw new Error("Code not found in message body");
  return m[1];
}

export function extractMagicLink(msg: Inbound, host: string): string {
  const urls = msg.body_text.match(/https:\/\/[^\s<>"]+/g) ?? [];
  const link = urls.find((u) => new URL(u).host === host);
  if (!link) throw new Error(`No link to ${host} found`);
  return link;
}

Follow three rules:

  • Check the sender. Only accept codes from the domain you expect. This blocks a stray or spoofed message from steering your flow.
  • Anchor on context. Match the surrounding phrase or a known code length, not a bare \d+.
  • Pin the link host. Magic link emails often contain tracking redirects, unsubscribe links and help-center links. Take only the URL on your app's host. Before following it, check whether a click-tracking wrapper sits in front.

Prefer body_text over HTML when the app sends both. It is easier to parse and less likely to hide the code inside table markup.

Step 4: Handle expiry and resends

OTPs expire, often within 5 to 15 minutes, and resends usually invalidate earlier codes. Handle both cases explicitly:

  1. Record triggeredAt just before you submit the form.
  2. Reject any message whose received_at is earlier than triggeredAt. This stops a leftover code from a previous run from being used.
  3. If you request a resend, clear the old waiter and wait again. Only use the newest code.
  4. If submitting the code returns "expired" or "invalid," retry the whole cycle once at most, then surface the failure.
  5. Don't log full codes or magic links. They are credentials while they are valid. Log the message ID and a masked value.

With per-task mailboxes, cleanup is simple. Delete or retire the mailbox when the task ends, so nothing ever arrives there for a waiter that no longer exists.

Where an email OTP API fits, and where it doesn't

This approach suits:

  • End-to-end tests of your own signup, login and password reset flows.
  • Agents operating accounts on internal tools or on services you administer.
  • Agents that legitimately hold accounts with vendors and need to log in on their own.

Be realistic about third parties. Some services block disposable-looking or newly created domains, require a phone number, cap accounts per domain, or forbid automated signups in their terms. A real mailbox makes delivery work. It does not grant permission. Use custom domains for anything that needs to look like an established sender, and only automate accounts you are entitled to operate. For the broader picture of agent mailboxes, see our email API for AI agents overview.

FAQ

Can I use one mailbox for many parallel tests?

You can, but you then need a second correlation key, such as a unique username in the subject, plus strict timestamp filtering. A mailbox per run removes the ambiguity.

Webhook or SSE for waiting on codes?

Use a webhook when your service has a public HTTPS endpoint. Use SSE when the waiter runs somewhere that can't receive inbound requests, like a developer machine or a restricted CI runner. The matching logic is the same for both.

What if the code arrives only in the HTML part?

First, have your app include a plain-text part, which also helps deliverability. If you can't change the app, strip tags from the HTML before you apply the same anchored regex.

Does this send OTP emails too?

No. This guide covers receiving. Your auth system or transactional mailer sends the codes. The mailbox just gives your agent somewhere real to receive them.

Ready to give your agents and test runners real inboxes they can read? Start with Robotomail and have a mailbox receiving verification emails in a few minutes.

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