How to Handle Email Verification in a Stagehand Browser Agent: Create an Address, Wait for the Code, Delete It
Let a Stagehand agent sign up with its own email address, read the verification code the moment it arrives, type it in, and delete the address when done.

Stagehand lets an agent use a browser with plain instructions: find the email field, click Create account. The step it cannot do alone is the one that follows a sign-up, reading the code the service emails. This tutorial adds that step: one agent, one address, one task. The script creates an address, the agent signs up with it, the code lands where the script can read it, and the address is deleted at the end.
It uses Stagehand’s observe() and act() with the Mailcycle TypeScript SDK. Mail is encrypted the moment it arrives, and the SDK opens it on the machine running the script.
Quick answer: how does a Stagehand agent read a verification code?
Create an address with mailcycle.addresses.create(), find the email field with observe() and fill it with the address, click submit with act(), then call mailcycle.messages.waitFor(). It resolves with the decrypted email; match the code in message.text, find the code field, fill it, and delete the address.
const message = await mailcycle.messages.waitFor({
inboxId: address.id,
since,
subject: 'verify',
timeoutMs: 90_000,
});
const code = message.text.match(/code is (\d{6})/)?.[1];
What you’ll build
One script, signup.mjs, that:
- Creates a Mailcycle address for the task.
- Opens a local browser with Stagehand and fills the sign-up form with the address.
- Waits for the verification email and types the code into the page.
- Deletes the address, whether the run worked or not.
The model finds the elements, and plain code carries the values. observe() returns real selectors for the fields, so the address and the code go from your script straight into the page.
Prerequisites
- Node.js 22 or later. The SDK is an ES module, so the script is
signup.mjs. - A model key. The example uses Anthropic through
ANTHROPIC_API_KEY; Stagehand takes other models too. - A Mailcycle account with an API key. API keys start at the Operator plan, and the free 7-day Scale trial includes them, with no card. Create the account in the web app.
- Your recovery phrase. Mail arriving at your addresses is sealed with keys derived from it, and the SDK opens it on the machine running the script.
- A sign-up you are allowed to use. A staging environment of your own product, or a service you have an account to try.
Step 1: Install Stagehand and the Mailcycle SDK
npm install @browserbasehq/stagehand@4.5.0 mailcycle-sdk@0.11.0
mailcycle-sdk has no dependencies and ships its own types. Stagehand launches a local Chrome for you.
Step 2: Create an API key
In the Mailcycle app, open API, then the Keys tab, name the key something like “Stagehand agent” and choose Create key. The token is shown once. Put it, your phrase, your model key and the sign-up URL in the environment the script runs in:
export MAILCYCLE_API_KEY="mak_..."
export MAILCYCLE_PHRASE="twelve words of your recovery phrase ..."
export ANTHROPIC_API_KEY="sk-ant-..."
export SIGNUP_URL="https://staging.example.com/signup"
Keep these out of version control. Locally, a .env file listed in .gitignore works with node --env-file=.env signup.mjs.
Step 3: Write the sign-up script
Create signup.mjs:
import { localBrowser, Stagehand } from '@browserbasehq/stagehand';
import { Mailcycle } from 'mailcycle-sdk';
const mailcycle = await Mailcycle.withApiKey({
apiKey: process.env.MAILCYCLE_API_KEY,
phrase: process.env.MAILCYCLE_PHRASE, // opens the mail on this machine
});
// One agent, one address, one task.
const address = await mailcycle.addresses.create({ prefix: 'agent', retentionDays: 1 });
const browser = await localBrowser.launch();
const stagehand = await Stagehand.create({
browser,
model: { modelName: 'anthropic/claude-sonnet-5-5', apiKey: process.env.ANTHROPIC_API_KEY },
});
try {
const [page] = await browser.context.pages();
await page.goto(process.env.SIGNUP_URL);
const since = new Date();
// The model finds the field; the address goes in as plain code.
const { data: emailInput } = await stagehand.observe('find the email input');
await page.locator(emailInput[0].selector).fill(address.emailAddress);
await stagehand.act('click the Create account button');
// The code lands in the address, and only the code goes back to the page.
const message = await mailcycle.messages.waitFor({
inboxId: address.id,
since,
subject: 'verify',
timeoutMs: 90_000,
});
const code = message.text.match(/code is (\d{6})/)?.[1];
if (!code) throw new Error(`No code in "${message.subject}"`);
const { data: codeInput } = await stagehand.observe('find the verification code input');
await page.locator(codeInput[0].selector).fill(code);
await stagehand.act('click the Verify button');
await page.waitForFunction("document.querySelector('h1')?.textContent === 'Welcome'");
console.log('Signed up and verified.');
} finally {
await stagehand.close();
await browser.close();
await mailcycle.addresses.delete(address.id); // the address and its mail
}
Run it with node signup.mjs. Change the instructions, the subject filter and the final check to match your page.
What each piece does:
Mailcycle.withApiKey({ apiKey, phrase })builds a client that can create addresses that receive mail and open what arrives. It checks that the phrase belongs to the key’s account, so a mismatched pair fails at the start withphrase_mismatch.addresses.create({ prefix: 'agent' })returns an address likeagent-7uf0@…: your prefix plus a random ending.retentionDays: 1clears any mail left behind after a day.observe()thenlocator().fill()is the pattern for any value the model should not carry: the model locates the input, and your script writes into it.sinceis taken before the form is submitted.waitForcounts mail fromsinceonwards, including mail that landed before the listener was up.subject: 'verify'is a case-insensitive “contains”, so it matches “Verify your email” and “Please verify your account”.fromworks the same way on the sender.- The
finallyblock closes Stagehand and the browser and deletes the address, so a failed run leaves nothing behind. A deleted address is retired and never issued to anyone again.
Links instead of codes
Some sign-ups send a link. Match the first link that points at the host you expect in message.text, and open it with page.goto(link) in the same page so the session stays in one browser.
Keep the email out of the model’s context
The script reads the email and gives the page six digits. It never passes the message body to a model. An email body is text from whoever sent it, so reading it in code, taking the part you need and acting on that keeps the agent on its task and keeps the run repeatable.
One address per run
The address is created at the start and deleted at the end, so the same script serves a one-off sign-up, a repeated check that your onboarding still sends its code, or an evaluation of an agent over many runs. Every run starts with a clean address and an empty inbox.
Or give the agent a standing inbox with the MCP server
If the agent should keep one inbox, pair it with mailcycle-mcp, the Mailcycle MCP server that runs on the agent’s own machine. It gives an MCP client tools to list mail, read a message and wait for the next one, and works with Claude Desktop, Cursor, Codex, VS Code or any other MCP client. Email MCP server: setup guide covers pairing.
Reuse what observe found with act
observe() returns candidate actions with a selector and a method. Passing one of them straight to act() runs it without asking the model to plan again, which saves a call and keeps the step repeatable.
const { data: [submit] } = await stagehand.observe('find the Create account button');
await stagehand.act(submit);
For a flow you run often, such as a nightly onboarding check, this pattern keeps cost and variance down. The model is asked once per element to find it, and your script decides what to do with the answer. The email part stays plain code on either side.
Pull the order or plan out with extract
Sign-ups often end with something worth recording: the plan the account landed on, the workspace name, or the order number in a receipt email. extract() takes a Zod schema and returns a typed object read from the page.
import { z } from 'zod';
const { data: welcome } = await stagehand.extract(
'read the welcome page',
z.object({ workspace: z.string(), plan: z.string() }),
);
console.log(welcome.workspace, welcome.plan);
For the email itself, prefer a regular expression over extract(). A six digit code is a pattern, and a pattern is exact, free and instant. Save the model for the page, where layout varies.
Handle a resend and a wrong code
Real sign-ups sometimes need a second code. If the first never arrives, click the resend control, take a new since and wait again. If the app rejects a code, request a new one rather than retrying the old digits.
async function codeFor(address, trigger) {
const since = new Date();
await trigger();
const message = await mailcycle.messages.waitFor({ inboxId: address.id, since, subject: 'verify', timeoutMs: 60_000 });
return message.text.match(/code is (\d{6})/)?.[1];
}
let code = await codeFor(address, () => stagehand.act('click Create account'));
if (!code) code = await codeFor(address, () => stagehand.act('click Resend code'));
Taking a fresh since each time means the second wait only matches the second email, so the first code can never be mistaken for the new one.
Run the check against several staging environments
Each run owns its own address and browser, so you can point the same script at staging and preview builds of your own app side by side. Keep the number small, since each run calls a model for the page steps.
Use agent mode for the page, keep the email in code
Stagehand’s agent mode can plan several page actions from one instruction. It suits a long form with many steps. The pattern that keeps things safe is to give the agent the page task up to the verification screen, then take over in your own code for the email.
const agent = stagehand.agent();
await agent.execute(`Fill the sign-up form with email ${address.emailAddress} and submit it. Stop at the verification screen.`);
Putting the address in the instruction is fine, because it is an address made for this run. The code should still go in from your script, as in the main example, so the message body never passes through the model.
Run it as a nightly check
A sign-up that sends email is one of the most valuable paths to watch, and a nightly run of this script tells you the moment the email stops arriving. Schedule it from CI, set SIGNUP_URL to staging, and fail the job on any exception. Because the address has a retention of one day and the finally block deletes it anyway, there is nothing to tidy afterwards. Send the job’s failure to the channel your team already watches, and include the step that failed, not the message text.
Why one address per run suits a browser agent
Each run of your onboarding check starts from a new address and an empty inbox, so a result never depends on mail from an earlier run. Name the prefix after the task, such as agent-onboarding-check, so you can tell which job created an address.
Cookie banners and other overlays
Overlays are the most common reason an act() step lands on the wrong element, so keep that step in front of every form step in the script.
Pages often put a banner or a dialog in front of the form. A plain act() that says “click Create account” can land on the banner instead. Add a short step first: await stagehand.act('accept the cookie banner if there is one'). Because the call is allowed to find nothing, it does no harm on pages without a banner. Keep that line in front of the form steps, and keep the email step unchanged, so the part that reads mail does not depend on how a particular site decorates its page.
When the email is slow
Most verification mail arrives in seconds, and waitFor() resolves the moment it does. When a site queues mail, the wait simply runs longer, up to the timeoutMs you set. Choose a ceiling that fits the site, such as 90 seconds for an ordinary sign-up and several minutes for one that sends through a batch queue. If the wait times out, the error has the code timeout, so you can catch it, take a screenshot of the page with page.screenshot() and fail with something a person can act on.
try {
message = await mailcycle.messages.waitFor({ inboxId: address.id, since, subject: 'verify', timeoutMs: 90_000 });
} catch (error) {
if (error.code === 'timeout') {
await page.screenshot({ path: 'no-email.png' });
throw new Error('No verification email within 90 seconds');
}
throw error;
}
A screenshot of a page that still shows the form tells you the click never submitted. A screenshot of “Check your email” tells you the site accepted the address and the mail is the missing piece.
Choosing between a code and a link
Sites verify in one of two ways, and the script handles both in a few lines. For a code, match the digits and type them into the field. For a link, match the first URL on the expected host and open it in the same page, so the browser session that started the sign-up is the one that finishes it. Check the host before you open anything: a link in an email is text from a sender, and the script should only follow links to the site it is working on.
const link = message.text.match(/https:\/\/app\.example\.com\/verify\?\S+/)?.[0];
if (!link) throw new Error('No verification link on the expected host');
await page.goto(link);
Log enough to debug, and no more
A browser agent run is hard to reproduce, so log what happened at each step: the page URL, the action taken, the address id and how long the email took. Do not log the message text, the code or the link, because those are credentials for the account you just made. A line such as waited 4.2s for message msg_91be, subject matched is enough to see that the mail path is healthy, and it is safe to keep in CI output for as long as you like.
Privacy of the run
Mail is encrypted the moment it arrives, with keys from your recovery phrase, and the SDK opens it on the machine that runs the script. The script gives the model the page and never the email body, so the model provider sees the page text and screenshots and not the message. Keep the phrase and the API key in environment variables, and keep .env out of version control. Delete the address at the end of the run, as the finally block does, and set a short retention as a second safety net.
Compare with other ways to give an agent an inbox
There are three ways to give a browser agent an inbox. The SDK, shown here, suits a script that owns the whole run: it creates the address, waits and deletes it. The MCP server suits an agent that should keep a standing address and decide for itself when to read mail, and Email MCP server setup for every client covers it. The API with a webhook suits a service that should react when mail arrives. Browser Use email verification shows the same job in Python for a different browser agent, and the code for the email half is the same shape.
Related guides
- Browser Use email verification
- Give an AI agent its own inbox in code
- Keep AI agents out of your personal inbox
- Email MCP server setup for every client
- Receive email in Node.js
- Test email verification in Playwright
Keep prompts short and selectors yours
Stagehand’s act() and observe() work best with short, specific instructions: “click the Create account button” rather than a paragraph. When observe() returns a selector you trust, store it in your script and use it directly on later runs, which saves a model call and removes variation. If your own app changes its markup, the failing observe() call tells you which element moved, and the email half of the script keeps working because it never depended on the page. Log the selector each observe() call chose, so a layout change shows up as a diff in your logs and you can decide whether to pin the new selector or let the model keep finding it.
Troubleshooting
waitFor rejects with code: 'timeout'. No matching email arrived in 90 seconds. Check that the click really submitted the form, that the subject filter matches the real subject, and that the service sends to outside addresses. Catch MailcycleError and log error.code to tell a timeout from an API error.
observe() returns the wrong field. Make the instruction more specific, for example “find the email input in the sign-up form”.
The check after the click fails at once. Submitting a form navigates, so wait for the next page with waitForFunction or waitForSelector rather than reading it straight away.
No "exports" main defined. The script is loading the SDK with require(). Use an .mjs file or set "type": "module" in package.json.
phrase_mismatch or 403 plan_required. The phrase belongs to a different account from the API key, or the account is on a plan without API keys. See Errors and Authentication.
Next steps
- Read the TypeScript SDK guide and the TypeScript SDK page for everything
messagesandaddressescan do. - See what a Mailcycle inbox gives an agent on the agents page.
- Prefer Python? Browser Use with a verification email does the same with custom tools.
- Testing your own sign-up from a test runner? Read Playwright email verification, Cypress or Selenium.
- Building an agent that reads and replies to mail? Give an AI agent its own email inbox.
FAQ
How do I handle an email verification step in Stagehand?
Create a Mailcycle address before the run, use observe() to find the email field, fill it with plain code (page.locator(selector).fill(address)), call act() to submit, then wait for the email with mailcycle.messages.waitFor() and fill the code the same way. Delete the address in a finally block.
Why fill the field with code instead of asking `act()` to type the address?
observe() returns real selectors, so the model only finds the field and your script puts the value in. The address and the code go straight from your code to the page, and the model never has to carry them. It also makes the step repeatable, because filling a located field behaves the same each time.
Do I need a Browserbase account?
No. The example launches a local browser with localBrowser.launch(). The same code works with a Browserbase session: change how the browser is launched and keep the Mailcycle calls as they are.
How long does the code take to arrive?
Usually a few seconds. waitFor() listens for new mail and resolves as soon as a matching message arrives, and it also counts mail that landed just before the listener started, so a fast service cannot beat the script to it.
Can I use the MCP server instead of the SDK?
Yes. mailcycle-mcp gives an MCP client tools to list, read and wait for mail in an agent's inbox, and it works with Claude Desktop, Cursor, Codex, VS Code or any other MCP client. The SDK in this guide also creates and deletes an address per task, which suits runs that start from a clean inbox.
Which Mailcycle plan do I need?
The examples use an API key with your recovery phrase, which needs the Operator plan or above. A script signed in with Mailcycle.signIn({ phrase }) can receive on every plan, Free included. See plans and limits.
Can Stagehand's agent mode handle the whole sign-up?
It can drive the page, but keep the email step in your own code. Let the agent fill the form and stop at the verification screen, read the code with waitFor(), then hand six digits back. The model never needs the message body.
Receive email in code
- AgentMail Alternative for AI Agent Inboxes (AgentMail alternative)
- CloudMailin Alternative: Inbound Email to Rails With an Address per API Call (CloudMailin alternative)
- Mailgun Inbound Routes Alternative: Route Mail by Address, Not Regex (Mailgun Routes alternative)
- Mailosaur Alternative for Email Testing and Test Inboxes (Mailosaur alternative)
- Mailparser and Parseur Alternative: Incoming Email as JSON on a Webhook (Mailparser and Parseur alternative)
- MailSlurp Alternative for Email Testing and Test Inboxes (MailSlurp alternative)
- Mailtrap Alternative for Email Testing and Test Inboxes (Mailtrap alternative)
- Postmark Inbound Alternative: Addresses by API, Signed Webhooks (Postmark inbound alternative)
- Resend Inbound Alternative: An Address per API Call, Signed Events (Resend inbound alternative)
- SendGrid Inbound Parse Alternative: Inbound Email by API Call (SendGrid Inbound Parse alternative)
- Testmail.app Alternative for Email Testing and Test Inboxes (Testmail.app alternative)
- Test Email Flows on Real Devices with Appium: Read Sign-Up Codes in Python (Appium)
- How to Give a Browser Use Agent an Email Address and Let It Read Its Own Verification Code (Browser Use sign-ups)
- How to Receive Email in C#: Read the Inbox, Save Attachments and Get New Mail Pushed (C# / .NET)
- How to Test Email Verification in Cypress: Receive Sign-Up Codes with cy.task (Cypress)
- Ethereal Email Alternative: Test Nodemailer Emails with an Address per Test (Ethereal Email alternative)
- Golang Receive Email: How to Receive and Read Email in Go (Go)
- How to Read Email in Java: Read the Inbox, Save Attachments and Receive Mail in Spring Boot (Java)
- How to Receive Email in PHP with an Email API: Read the Inbox, Save Attachments and Handle Webhooks (PHP / Laravel)
- How to Receive Email in Python: Read the Inbox, Save Attachments and Get New Mail Pushed (Python)
- Receive Email in Ruby and Rails: Read the Inbox, Save Attachments and Handle Webhooks (Ruby)
- How to Receive Email in Rust: Read the Inbox, Save Attachments and Handle Webhooks in Axum (Rust)
- Add Inbound Email to Your SaaS: Support Intake and Reply-by-Email (SaaS support)
- How to Verify Email in Selenium Tests: Read Sign-Up Codes with Python and pytest (Selenium)
- How to Receive Email in Swift: Read the Inbox, Save Attachments and Handle Vapor Webhooks (Swift)
- Test Accounts for Security Testing: a Separate Email Address per Program (Test accounts for security testing)
- How to Automate Email Verification in Tests with Playwright: OTP Codes, Magic Links and Password Resets (Testing email verification)
- How to Receive Email in Node.js: Read the Inbox, Save Attachments and Handle Webhooks (TypeScript / Node.js)
- How to Receive Email with a Webhook: Inbound Email to Your HTTP Endpoint (Webhooks)