All posts
Guide·Jul 7, 2026·8 min read

How to receive OTP and verification codes with an email API

Receive OTP and verification codes programmatically with a real inbox and a webhook, parse the code with a regex, and let an AI agent finish the signup.

Dvir Atias

Dvir Atias

Founder

To receive an OTP or verification code from code, you need three things: a real email inbox you can create and read over an API, a way to be told the moment a message lands in it, and a small parser that pulls the code out of the body. The pattern is always the same. Create an inbox, use its address to sign up, wait for the verification email either by webhook or by polling, then extract the code with a regular expression like \b\d{6}\b. This turns the classic "we sent a code to your email" wall into a normal, automatable step, whether the caller is a test suite, a background job, or an autonomous AI agent.

The problem: agents get stuck at the verification wall

Almost every signup, password reset, and two-factor login now routes through email. The service sends a one-time password or a confirmation link to an address, and the flow refuses to continue until someone reads that message and types the code back in. For a human this is a two-second detour. For anything automated it is a hard stop.

An agent or a script does not have a mailbox open in a browser tab. If it registers with a real person's Gmail address, the code lands somewhere the code cannot see, and scraping a shared human inbox over IMAP is slow, fragile, and mixes the agent's mail in with everyone else's. What the automation actually needs is a mailbox that is itself programmable: an address it owns, that it can read from a function call, that fires an event when mail arrives. That is exactly what an email API provides, and it is a core reason AI agents need their own inbox rather than borrowing a human's.

The pattern: a programmable inbox plus an event

Every reliable OTP-retrieval flow is built from the same four moves.

  1. Create an inbox via the API. You call an endpoint and get back a live address like signup-bot@inbox.agenticemail.dev plus an inbox id. This address is real, so any service that emails it will actually deliver.
  2. Use it as the signup address. Drive your registration, reset, or 2FA flow against that address just as a human would.
  3. Learn when the message arrives. This is the only interesting design choice, and there are two ways to do it.
  4. Parse the code out of the body. Inbound mail arrives already parsed into structured fields, so you run a regular expression over the plain text and pull the digits.

The choice in step three is webhook versus wait-and-poll, and the tradeoff is short.

A webhook is push. You register an HTTPS endpoint once, and the platform sends you an HTTP request with the fully parsed message the instant it is received. This is the right choice for anything long-running: an always-on agent or a service handling many signups. The cost is that you need a reachable URL and a small handler. The email webhook guide covers setup and signature verification in full.

Wait-and-poll is pull. Your code asks the inbox for its messages on a short loop, or uses a single blocking call that returns as soon as a message shows up. This is the right choice for a script, a test, or a one-shot task where a process is already sitting there waiting for the code. It is simpler because there is no public URL involved. The cost is a held-open loop and a timeout you have to pick.

Neither is more correct. Use a webhook when something is always listening, use wait-and-poll when a single process just needs one code and then moves on.

Example

Here is the full flow with AgenticEmail. Every request authenticates with a bearer token against the REST base at https://api.agenticemail.dev (Authorization: Bearer $AGENTICEMAIL_API_KEY), and the CLI and SDKs wrap the same endpoints.

1. Create a per-task inbox.

agenticemail inboxes create

The response includes an inbox id like ibx_123 and a live address such as signup-bot@inbox.agenticemail.dev. Use that address as the email you submit to the service you are signing up for.

2a. Wait for the message from the command line.

For a script or a one-shot task, block on the inbox until the verification email lands or a timeout is hit.

agenticemail wait-for-message ibx_123 --timeout 300

This returns as soon as a message arrives, so your automation can grab the body and extract the code without a hand-rolled polling loop.

2b. Or register a webhook for real-time delivery.

For an always-on agent, subscribe once and let each inbound message be pushed to your handler.

agenticemail webhooks create --url https://your-app.com/hooks/otp --event-types message.received

Now every message that hits any of your inboxes is delivered to that URL as a signed JSON payload, so there is nothing to poll.

3. Extract the code with the SDK.

Whether you woke up from a webhook or from wait-for-message, the extraction step is the same: read the message and run a regex over the text. Here it is in Python using the SDK (pip install agenticemail), listing the inbox, fetching the full message, and pulling a 6-digit code.

import os
import re
import time

from agenticemail import AgenticEmail

client = AgenticEmail(api_key=os.environ["AGENTICEMAIL_API_KEY"])

def wait_for_code(inbox_id, timeout=300):
    deadline = time.time() + timeout
    while time.time() < deadline:
        result = client.messages.list(inbox_id=inbox_id)
        if result.messages:
            latest = result.messages[0]
            message = client.messages.get(message_id=latest.id)
            match = re.search(r"\b\d{6}\b", message.text or "")
            if match:
                return match.group(0)
        time.sleep(3)
    raise TimeoutError("verification code did not arrive in time")

code = wait_for_code("ibx_123")
print(code)

Because inbound mail arrives already parsed, you never touch raw MIME. The sender, subject, and body are plain fields, so re.search(r"\b\d{6}\b", message.text) is usually all it takes to isolate the code. If a service ships codes of a different length, adjust the pattern (for example \b\d{4}\b or \b[A-Z0-9]{8}\b), and if several numbers appear, narrow the search to the line that mentions "code" or "verify".

That is the entire loop: one inbox, one wait or webhook, one regex. The same primitives back every use case in the temp mail API guide, from signup QA to OTP retrieval.

Security and etiquette

Receiving codes from code is a normal engineering task, but it touches secrets and other people's systems, so a few rules matter.

  • Only automate signups you are authorized to run. Sign up your own service, your own test accounts, or accounts a customer has explicitly asked you to create. Do not use automated verification to create fake accounts, evade bans, or register on a platform that forbids it.
  • Treat codes as secrets. A verification code is a short-lived credential. Keep it in memory, pass it straight into the step that needs it, and never write it to logs, error trackers, or analytics. Redact it before anything gets persisted.
  • Respect provider terms. Some services prohibit automated signups outright. Read the terms, and when in doubt use an official API or a sandbox instead of driving the human signup form.
  • Use per-task inboxes. Create a fresh inbox for each signup so one task's codes are isolated from another's. If a key or an inbox is ever exposed, the blast radius is a single mailbox rather than every code your system has ever received. This is the same isolation argument behind giving your agent an inbox it fully controls.

Handled this way, automated verification stays boring in the good sense: predictable and contained.

Frequently asked questions

Can I receive OTP codes with an API instead of a phone?

Yes. Email one-time passwords are just messages delivered to an address, so any email API that lets you create and read an inbox lets you receive them from code. With AgenticEmail you create an inbox, use its address at signup, and read the code from the parsed message, no SMS gateway or phone number involved.

How do I get the inbound email in real time?

Register a webhook for the message.received event, and each incoming message is pushed to your HTTPS endpoint as parsed JSON the moment it arrives. If you would rather not run a public URL, use agenticemail wait-for-message <inbox> --timeout 300, which blocks and returns as soon as a message lands. The email webhook guide walks through the push setup.

How do I extract the code from the email?

Read the message and run a regular expression over its plain text field. A pattern like \b\d{6}\b isolates a standard 6-digit code, and because inbound mail is already parsed into structured fields you never have to decode raw MIME yourself. If the body contains more than one number, scope the match to the line that mentions verifying or a code.

Is it against the rules to automate email verification?

It depends on the service. Automating verification for your own accounts, test suites, or authorized customer signups is a routine practice, but some platforms prohibit automated registration in their terms. Read the terms first, prefer an official API or sandbox where one exists, and never use automated verification to create fraudulent accounts.

Can an AI agent complete a signup that needs email verification?

Yes, and it is a primary use case. Give the agent an inbox from the API, let it submit that address during signup, deliver the verification email over a webhook or a blocking wait, and have the agent parse the code and enter it. The full pattern is covered in what an AI email agent is and how to build one, and every endpoint and SDK method lives in the docs.

Talk to a real person