Guide · Agents
Give a browser or LLM agent an inbox for sign-ups
Browser agents can click through a sign-up form on their own. What they cannot do is open an inbox to read the six-digit code the site sends next. Handing them your personal mailbox means IMAP credentials in a prompt-driven program, which is the wrong trade.
This guide gives an agent two small tools backed by a dedicated, receive-only inbox: one to prepare, one to wait for the code. They are plain functions with a JSON schema, so they fit the OpenAI Agents SDK, LangChain, a browser-use style loop or your own tool-calling code.
Last reviewed:
The flow
Step 1
Prepare
The agent calls prepare_email_verification. Your code reads the newest message id and returns it with the fixed address.
Step 2
Fill and submit
The browser agent types the address into the form and submits it, as it would any other field.
Step 3
Wait
The agent calls get_verification_code with that since. One long-poll returns as soon as newer mail lands.
Step 4
Finish
The tool returns the code and link already extracted. The agent types the code or opens the link.
Two design choices do most of the work. The address is fixed in your code, not chosen by the model. And the “since” marker is taken before the form is submitted, which is the only reliable way to avoid an old code.
The two tools
Both functions call the REST API with an sk_live_ key limited to one inbox, sent as X-API-Key. get_verification_code long-polls with since and wait=25, moves its marker forward past mail that does not match the sender filter, and returns the first message that has a code or a link.
# inbox_tools.py (pip install requests)
import os, time, requests
API = "https://api.restapi.email"
INBOX = os.environ["AGENT_INBOX"] # e.g. signup-bot@agent.restapi.email
HEADERS = {"X-API-Key": os.environ["RESTAPI_EMAIL_KEY"]} # sk_live_ key limited to INBOX
def _page(**params) -> dict:
r = requests.get(f"{API}/api/v1/emails/{INBOX}/messages", params=params,
headers=HEADERS, timeout=params.get("wait", 0) + 10)
r.raise_for_status()
return r.json()
def _list(**params) -> list[dict]:
return _page(**params)["emails"]
def _all_since(after: str, wait: int) -> list[dict]:
"""Every message after 'after', newest first: the first page may wait,
later pages follow the cursor so nothing in the window is skipped."""
body = _page(since=after, wait=wait, limit=50)
emails = list(body["emails"])
while body["pagination"]["has_more"]:
body = _page(since=after, limit=50, cursor=body["pagination"]["next_cursor"])
emails += body["emails"]
return emails
def prepare_email_verification() -> dict:
"""Call BEFORE submitting a sign-up form. Returns the address to type
into the form and a 'since' marker for get_verification_code."""
emails = _list(limit=1)
return {"address": INBOX,
"since": emails[0]["id"] if emails else "1970-01-01T00:00:00Z"}
def get_verification_code(since: str, from_contains: str | None = None,
timeout_seconds: int = 120) -> dict:
"""Wait for a verification email that arrived after 'since' and return
its one-time code and/or verification link."""
deadline = time.monotonic() + timeout_seconds
after = since
while time.monotonic() < deadline:
wait = max(1, min(25, int(deadline - time.monotonic())))
emails = _all_since(after, wait) # the whole window, all pages
if not emails:
continue
after = emails[0]["id"] # every message up to here gets checked below
for summary in emails:
if from_contains and from_contains.lower() not in (summary["from"] or "").lower():
continue
r = requests.get(f"{API}/api/v1/emails/{INBOX}/messages/{summary['id']}",
headers=HEADERS, timeout=15)
r.raise_for_status()
email = r.json()["email"]
codes, links = email["extracted"]["codes"], email["extracted"]["links"]
if codes or links:
return {"code": codes[0] if codes else None,
"link": links[0] if links else None,
"subject": email["subject"], "from": email["from"]}
return {"timed_out": True, "hint": "Call again with the same since."}// inboxTools.ts (Node 18+, global fetch)
const API = 'https://api.restapi.email';
const INBOX = process.env.AGENT_INBOX!; // e.g. signup-bot@agent.restapi.email
const headers = { 'X-API-Key': process.env.RESTAPI_EMAIL_KEY! }; // sk_live_ limited to INBOX
type Summary = { id: string; from: string | null };
async function page(params: Record<string, string | number>) {
const qs = new URLSearchParams(Object.entries(params).map(([k, v]) => [k, String(v)]));
const res = await fetch(`${API}/api/v1/emails/${INBOX}/messages?${qs}`, { headers });
if (!res.ok) throw new Error(`list failed: ${res.status}`);
return (await res.json()) as { emails: Summary[]; pagination: { has_more: boolean; next_cursor: string | null } };
}
async function list(params: Record<string, string | number>) {
return (await page(params)).emails;
}
// Every message after 'after', newest first; later pages follow the cursor
// so a busy inbox cannot push the verification email out of the window.
async function allSince(after: string, wait: number) {
let body = await page({ since: after, wait, limit: 50 });
const emails = [...body.emails];
while (body.pagination.has_more && body.pagination.next_cursor) {
body = await page({ since: after, limit: 50, cursor: body.pagination.next_cursor });
emails.push(...body.emails);
}
return emails;
}
export async function prepareEmailVerification() {
const [newest] = await list({ limit: 1 });
return { address: INBOX, since: newest?.id ?? '1970-01-01T00:00:00Z' };
}
export async function getVerificationCode(
since: string, fromContains?: string, timeoutSeconds = 120,
) {
const deadline = Date.now() + timeoutSeconds * 1000;
let after = since;
while (Date.now() < deadline) {
const wait = Math.max(1, Math.min(25, Math.floor((deadline - Date.now()) / 1000)));
const emails = await allSince(after, wait); // the whole window, all pages
if (emails.length === 0) continue;
after = emails[0].id;
for (const summary of emails) {
if (fromContains && !(summary.from ?? '').toLowerCase().includes(fromContains.toLowerCase())) continue;
const res = await fetch(`${API}/api/v1/emails/${INBOX}/messages/${summary.id}`, { headers });
if (!res.ok) throw new Error(`detail failed: ${res.status}`);
const { email } = await res.json();
const { codes, links } = email.extracted;
if (codes.length || links.length) {
return { code: codes[0] ?? null, link: links[0] ?? null, subject: email.subject, from: email.from };
}
}
}
return { timed_out: true, hint: 'Call again with the same since.' };
}The list endpoint returns summaries newest first; the code and link come from the message detail, which carries extracted.codes and extracted.links. Links wrapped by Gmail, Outlook Safe Links or Proofpoint are unwrapped, and unsubscribe and tracking links are left out.
Tool schema (framework-agnostic)
If your framework takes JSON tool definitions, this is all the model needs to see. Note what is missing: no address argument and no key. The model cannot point the tool at another inbox.
[
{
"type": "function",
"name": "prepare_email_verification",
"description": "Call before submitting a sign-up or login form that will email a code. Returns the email address to enter and a 'since' marker.",
"parameters": { "type": "object", "properties": {}, "additionalProperties": false }
},
{
"type": "function",
"name": "get_verification_code",
"description": "Wait (up to 2 minutes) for the verification email that arrived after 'since'. Returns {code, link, subject, from} or {timed_out: true}; on timed_out, call again with the same since.",
"parameters": {
"type": "object",
"properties": {
"since": { "type": "string", "description": "The since value from prepare_email_verification." },
"from_contains": { "type": "string", "description": "Optional sender filter, e.g. the site's domain." }
},
"required": ["since"],
"additionalProperties": false
}
}
]The format follows the common function-calling shape. Some APIs nest the same fields under a function key; the names, descriptions and parameters stay the same.
Register the tools with your framework
# OpenAI Agents SDK (pip install openai-agents)
from agents import Agent, Runner, function_tool
import inbox_tools
@function_tool
def prepare_email_verification() -> dict:
"""Call before submitting a sign-up form. Returns the address and a since marker."""
return inbox_tools.prepare_email_verification()
@function_tool
def get_verification_code(since: str, from_contains: str | None = None) -> dict:
"""Wait for the verification email after 'since'; returns code and link."""
return inbox_tools.get_verification_code(since, from_contains)
agent = Agent(
name="signup-agent",
instructions=("When a site asks for an email address, call prepare_email_verification "
"first, enter the address it returns, submit, then call "
"get_verification_code with the since it returned."),
tools=[prepare_email_verification, get_verification_code], # plus your browser tools
)# LangChain (pip install langchain-core)
from langchain_core.tools import tool
import inbox_tools
@tool
def prepare_email_verification() -> dict:
"""Call before submitting a sign-up form. Returns the address and a since marker."""
return inbox_tools.prepare_email_verification()
@tool
def get_verification_code(since: str, from_contains: str | None = None) -> dict:
"""Wait for the verification email after 'since'; returns code and link."""
return inbox_tools.get_verification_code(since, from_contains)
tools = [prepare_email_verification, get_verification_code]
# llm.bind_tools(tools), or pass tools to your agent constructorFor browser-use style agents, register the same two functions through the framework’s custom-action or tool mechanism and keep the instruction text: “call prepare_email_verification before you submit a form that asks for an email”. The wait blocks for up to two minutes, so in an async runtime use an async HTTP client or run the call in a worker thread.
Or skip the glue: use MCP
If your framework can connect to a remote MCP server over Streamable HTTP with a custom header, point it at https://api.restapi.email/mcp. The get_verification_code tool there does the same wait and extraction, with from_contains and subject_contains filters. Setup for each client is on the MCP page, and a walkthrough for Claude Code is in the Claude Code guide.
{
"mcpServers": {
"restapi-email": {
"type": "http",
"url": "https://api.restapi.email/mcp",
"headers": { "X-API-Key": "sk_live_..." }
}
}
}Pitfalls
Old codes
Without since, the newest message in the inbox matches immediately, even if it is the code from the last run. Always call prepare_email_verification first. If the agent clicks “resend code”, the original marker still works: the newest matching email wins.
The wrong sender
One inbox may receive a newsletter and a code in the same minute. Pass from_contains with the site’s domain. Note the filter matches the From header, and some services send from a different domain than their website.
Timeouts
Some services take minutes. The tool returns timed_out instead of throwing, and the description tells the model to call again with the same since. Nothing that arrives in between is missed.
No code found
Extraction is a heuristic. When a message has neither a code nor a link, the tool skips it. If that happens with a service you care about, add a fallback that returns text_content for the model to read, and treat that text as untrusted: email can contain instructions written for your agent.
Rate limits
About 120 requests a minute per key, and up to 30 long polls a minute. Many agents in parallel should use several inboxes and keys.
What this does not do
- Send or reply to email: the inbox is receive-only.
- Solve CAPTCHAs or get around a service’s terms of use.
- Keep attachments: they are discarded before storage.
- Keep mail forever: messages are deleted after 30 days, or earlier with DELETE or the delete_message tool.
If your agent needs to send, reply in threads or use your own domain, a full agent mailbox such as AgentMail is the better fit; see the comparison.
Questions
Which agent frameworks does this work with?
Any that can call a function or an MCP server. The guide defines two plain functions and a JSON tool schema, then shows them registered with the OpenAI Agents SDK and LangChain; MCP-capable clients can use the remote MCP server instead.
Should the model choose which inbox to read?
No. Fix the address in your tool code and use an sk_live_ key limited to that one inbox, so a confused or manipulated model cannot read other mail.
What if the extracted code is wrong or missing?
Extraction is a heuristic and leaves codes empty rather than guess. The message detail still has text_content and html_content, so the tool can return the text for the model to read when no code is found.
Can RESTAPI.email solve CAPTCHAs or reply to the email?
No. It is receive-only and does nothing about CAPTCHAs or a service’s terms. Use it where your agent is allowed to sign up.