How to Give a Browser Use Agent an Email Address and Let It Read Its Own Verification Code

Give a Browser Use agent one email address per task: it signs up, the verification code lands where it can read it, and the address is deleted afterwards.

By · · 12 min read

Python code from this guide, in signup_agent.py, running a Browser Use agent with tools for an email address and code

A browser agent that signs up for something needs one thing a browser cannot give it: an email address it can read. The service sends a six-digit code, the agent has to find it, and the task stalls unless the code lands somewhere the agent can reach. This tutorial gives a Browser Use agent that address: one agent, one address, one task. The agent creates the address, signs up with it, reads the code, finishes, and deletes the address.

It uses Browser Use 1.0, where you add your own abilities with @tools.action, and the mailcycle Python package. Mailcycle gives each agent a real address and delivers mail to it as it arrives. Mail is encrypted the moment it arrives, and the package opens it on the machine running the agent.

Quick answer: how does a Browser Use agent read a verification code?

Add three tools to the agent: new_email_address, wait_for_verification_code and delete_email_address. The agent calls the first before it fills in the form, the second after it submits, and the third when it is done.

@tools.action("Wait for the verification email and return the 6-digit code from it. Call after submitting the form.")
def wait_for_verification_code() -> str:
    email = mailcycle.messages.wait_for(address_id=address.id, subject="verif", since=since, timeout=90)
    match = re.search(r"\b\d{6}\b", email.text)
    return match.group(0) if match else "The email arrived but has no 6-digit code."

The rest of this guide builds the other two tools, the task prompt and the run.

What you’ll build

By the end you’ll have one Python file, signup_agent.py, with:

  • A Tools object holding three actions the agent can call.
  • A task prompt that tells the agent when to call each one.
  • A main() that runs the agent in a local Chrome.

The flow in every run is the same: the agent asks for an address, types it into the sign-up form, the service emails a code, the agent asks for the code, types it in, and deletes the address. The model never sees the recovery phrase or the API key, and it only sees the six digits, not the email.

Flow: a Browser Use agent signs up with a fresh address, the app sends a verification email, Mailcycle receives it encrypted on arrival, and the code is read to finish sign-up
A Browser Use agent signs up with a Mailcycle address, waits for the verification email and reads the code from it.

Prerequisites

  • Python 3.11 or later and a model key. The example uses Anthropic through ANTHROPIC_API_KEY; Browser Use also takes other models.
  • 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 package opens it on the machine running the agent.
  • A sign-up you are allowed to use. A staging environment of your own product, or a service you have an account to try. The example URL is https://staging.example.com/signup.

Step 1: Install Browser Use and the Mailcycle package

python3 -m venv .venv && source .venv/bin/activate
pip install 'browser-use==1.0.9' 'mailcycle[events]==0.8.0'

Browser Use asks for an exact pin because releases move quickly, so keep the ==. The events extra adds websockets, so the wait hears new mail as it arrives; without it, the package checks the address every five seconds.

Step 2: Create an API key

In the Mailcycle app, open API, then the Keys tab, name the key something like “Browser agent” and choose Create key. The token is shown once. Put it, your phrase and your model key in the environment the agent runs in:

export MAILCYCLE_API_KEY="mak_..."
export MAILCYCLE_PHRASE="twelve words of your recovery phrase ..."
export ANTHROPIC_API_KEY="sk-ant-..."

Keep all three out of the task prompt and out of version control. Browser Use passes the task text to the model, and none of these belong in it.

Step 3: Write the three tools

Create signup_agent.py:

import os
import re
from datetime import datetime, timezone

from browser_use import Agent, Browser, ChatAnthropic, Tools
from mailcycle import Address, Mailcycle

mailcycle = Mailcycle.with_api_key(
    os.environ["MAILCYCLE_API_KEY"],
    phrase=os.environ["MAILCYCLE_PHRASE"],  # opens the mail on this machine
)
tools = Tools()

# One agent, one address, one task.
address: Address | None = None
since: datetime | None = None


@tools.action("Create the email address for this task. Returns the address to type into the sign-up form.")
def new_email_address() -> str:
    global address, since
    since = datetime.now(timezone.utc)
    address = mailcycle.addresses.create(prefix="agent", label="sign-up task", retention_days=1)
    return address.email_address


@tools.action("Wait for the verification email and return the 6-digit code from it. Call after submitting the form.")
def wait_for_verification_code() -> str:
    if address is None or since is None:
        return "No address yet: call new_email_address first."
    email = mailcycle.messages.wait_for(address_id=address.id, subject="verif", since=since, timeout=90)
    match = re.search(r"\b\d{6}\b", email.text)
    # Hand the model the code, not the email: a message body is data from a stranger.
    return match.group(0) if match else "The email arrived but has no 6-digit code."


@tools.action("Delete the task's email address and its mail. Call once the sign-up is finished.")
def delete_email_address() -> str:
    global address
    if address is not None:
        mailcycle.addresses.delete(address.id)
        address = None
    return "Address deleted."

What each piece does:

  • Mailcycle.with_api_key(key, 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 with phrase_mismatch.
  • addresses.create(prefix="agent") returns an address like agent-7uf0@…: your prefix plus a random ending. The label is sealed with the address and records what the address is for. retention_days=1 clears any mail left behind after a day.
  • since is the time the address was created. wait_for counts mail from since onwards, including mail that landed before the listener was up, so a fast service cannot beat the agent to it.
  • messages.wait_for(...) returns the next matching message, already decrypted. The subject filter is a case-insensitive “contains”, so "verif" matches “Verify your email” and “Your verification code”.
  • addresses.delete() removes the address and its mail. A deleted address is retired and never issued to anyone again.

The descriptions matter: they are the text the model reads when it decides which tool to call, so say when each one is used.

Step 4: Give the agent its task and run it

Add the task and a main() to the bottom of the file:

TASK = """Open https://staging.example.com/signup. Call new_email_address and use that address in the
form, then submit it. When the page asks for a code, call wait_for_verification_code, type the code and
verify. When the page says Welcome, call delete_email_address and report what the page says."""


def main(llm=None, url: str = "https://staging.example.com/signup") -> str | None:
    agent = Agent(
        TASK.replace("https://staging.example.com/signup", url),
        llm=llm or ChatAnthropic("claude-sonnet-5-5"),  # ANTHROPIC_API_KEY
        browser=Browser("chromium"),  # a fresh local Chrome with its own temporary profile
        tools=tools,
    )
    return agent.run_sync().final_result()


if __name__ == "__main__":
    print(main())

Run it with python signup_agent.py. Browser Use opens a fresh Chrome, and the agent works through the page: it calls new_email_address, fills the form with the address it gets back, submits, calls wait_for_verification_code while the service sends its email, types the digits, and calls delete_email_address when the page says Welcome.

The task prompt names the tools in the order to call them. A model follows an explicit sequence more reliably than one it has to work out, and the sequence keeps the address alive exactly as long as the task.

Why the tool returns the code, not the email

wait_for_verification_code could return email.text and let the model read it. It returns six digits instead. The sender of an email is whoever the service says it is, and the body can contain anything, including text that looks like an instruction. Returning only the code means the model reads a number and nothing else from the message, and the agent stays on its task.

If a service sends a link instead of a code, do the same: match the link on the host you expect in email.text and return that link.

One address per run, for repeatable checks

Because the address is created and deleted inside the run, the same file works for repeated runs: an evaluation of how well an agent completes sign-ups, a nightly check that your own onboarding still sends its code, or a demo. Every run starts with a new address and an empty inbox, and finishes with nothing left behind. If a run stops early, retention_days=1 clears the mail the next day.

Or give the agent a standing inbox with the MCP server

The SDK route above creates a new address each time. If the agent should instead 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 it works with Claude Desktop, Cursor, Codex, VS Code or any other MCP client. Email MCP server: setup guide covers pairing, and Browser Use can call an MCP server from a plain @tools.action function.

Keep the account password out of the prompt

A sign-up needs a password as well as an address, and a model does not need to see it. Browser Use accepts a sensitive_data dictionary on the agent. The task names a placeholder, and the library substitutes the real value when it types.

agent = Agent(
    TASK + " Use x_password as the password.",
    llm=ChatAnthropic("claude-sonnet-5-5"),
    browser=Browser("chromium"),
    tools=tools,
    sensitive_data={"x_password": os.environ["TEST_ACCOUNT_PASSWORD"]},
)

The same idea applies to the email half: the tool returns six digits and nothing else, so the model never reads the body of a message. Between them, the model sees neither the password nor the email, and your logs carry only placeholders.

Cap the run with max_steps

A browser agent that gets confused can wander. run_sync takes a step limit, and the limit is the cheapest guard you have against a run that loops on a changed page.

history = agent.run_sync(max_steps=25)
print(history.final_result())

Choose a number a little above what a good run takes. If a run hits the limit, treat it as a failed check, take the history’s last screenshot and look at the page, since a changed layout or a new consent step is the usual cause. Because the address is deleted by the task’s last tool call, add a finally in your wrapper that deletes it too, so a run that ends early leaves nothing behind.

Wrap the agent in a pytest check

An agent run is a test if you assert on the result. Wrap main() in a test, give it a generous timeout and fail on anything but the welcome text.

import os

import pytest
import signup_agent

@pytest.mark.integration
def test_onboarding_sends_code_and_verifies():
    try:
        result = signup_agent.main(url=os.environ["SIGNUP_URL"])
        assert result and "Welcome" in result
    finally:
        if signup_agent.address is not None:
            signup_agent.mailcycle.addresses.delete(signup_agent.address.id)

Mark it with integration and run it on a schedule rather than on every commit, since it calls a model and waits for a real email. A failing run is a signal that either the page changed or the email stopped arriving, and the agent’s history, with its screenshots, tells you which.

Async runs and several agents

run_sync suits a script. In an async service, use await agent.run(), and run several agents side by side with asyncio.gather. Each agent needs its own address and its own since, so the module-level address global above becomes a small class or a closure per agent.

class SignupTools:
    def __init__(self, prefix: str):
        self.tools, self.address, self.since = Tools(), None, None
        # register new_email_address, wait_for_verification_code, delete_email_address on self.tools

One tools object per agent is what keeps two runs from reading each other’s mail. Cap the number running at once with a semaphore, because each agent calls a model on every step.

Limit where the browser may go

An agent follows the instructions on the pages it visits, and a page can contain text that tries to steer it. Browser Use lets you limit the domains the browser may open. Set that to the site under test, so a stray link in a page or an email cannot take the agent somewhere else. The tool that waits for the email returns only a code, and the task should say where the code goes, which leaves little room for anything else to happen.

Debug a stuck run

When a run does not finish, look at the history before the code. The last few steps show the page the agent saw and the action it chose. If the agent keeps calling wait_for_verification_code, check the address in the Mailcycle app: an empty inbox means the site never sent mail, which is a finding about the site, not the agent. If the agent typed the address into the wrong field, make the tool’s description clearer, because it is the text the model reads when it chooses. Run the same task with a short max_steps while you fix it, so each attempt is cheap.

Plenty of sites send a link. Add a fourth tool that returns the first link on the expected host, and let the task tell the agent to open it in the current tab.

@tools.action("Wait for the verification email and return the confirmation link. Call after submitting the form.")
def wait_for_verification_link() -> str:
    email = mailcycle.messages.wait_for(address_id=address.id, subject="confirm", since=since, timeout=90)
    match = re.search(r"https://app\.example\.com/confirm\S+", email.text)
    return match.group(0) if match else "No confirmation link on the expected host."

Filtering by host in the tool matters. A message is text from a sender, and the link the agent opens should only ever point at the site it is working on. The tool returns a single URL, and the agent never reads the rest of the message.

What to do when the email is late

A sign-up email normally lands in seconds, and the wait returns as soon as it does. If your staging provider queues mail, raise the timeout on the wait and tell the agent in the task that the code can take a minute. A model that is told to expect a delay waits for the tool, while one that is not may decide the page is broken and start clicking. When the wait times out, the tool should return a plain sentence such as “No email arrived in 90 seconds”, so the agent can report that and stop, rather than raising an exception that ends the run without a message.

A weekly onboarding check

The most useful thing to do with this script is to run it on a schedule. Once a week, or every night, run the agent against staging and compare the final text with what you expect. Because each run creates a fresh address and deletes it at the end, the check is repeatable, and a failure points at one of three things: the page, the email or the model. Keep the history of each run for a few days, and keep the address prefix constant so the leftover addresses, if any, are easy to find.

Privacy and security 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 agent. The tools return only what the task needs, a code or a link, so the model provider sees the page and the six digits and not the message. Keep the recovery phrase and the API key in environment variables and out of the task text. Remember that an email body can hold instructions written by a stranger, which is one more reason the tool returns a value and not the body.

Keep the tools file small

The three tools are the whole mail surface the agent has, so keep them in one short module that you can read in a minute. A reviewer then sees at a glance that the agent can create an address, wait for a code and delete the address, and nothing else.

Troubleshooting

wait_for raises a timeout. No matching email arrived in 90 seconds. Check that the form really submitted (the agent’s last step in the log), that the sign-up sends to outside addresses, and that the subject filter matches the real subject.

The agent never calls the tools. Say when to call each one in the task, as in the example, and keep the tool descriptions short and specific.

The agent types the code before the email arrives. The wait blocks until the email arrives, so the agent only gets a code back once there is one. If your model skips the call, name the order in the task.

It found an older email. Each task creates a new address and takes since at the same moment, so an older email cannot match. If you reuse one address across tasks, take since right before the submit instead.

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

FAQ

How does a Browser Use agent get a verification code from email?

Give the agent three custom tools: one that creates an email address, one that waits for the verification email and returns the code, and one that deletes the address. The agent types the address into the sign-up form, calls the wait tool, types the code it gets back, and finishes. With Mailcycle the tools are a few lines each with the mailcycle Python package.

How do I add custom tools to a Browser Use agent?

Create a Tools() object, decorate plain Python functions with @tools.action('what the action does'), and pass it to the agent with Agent(task, tools=tools). The function's name, arguments and description are what the model sees. Return a short string; the model reads it as the tool result.

Should the agent read the whole email or just the code?

Just the code. The tool matches the six digits in the message and returns only those, so the model never has to read the rest of the body. An email body is text from whoever sent it, so keeping it out of the model's context is the simpler design.

How many addresses should an agent use?

One per task. The agent creates its address at the start, uses it for the sign-up, and deletes it when the task is done. The next run starts with a clean address, so an old code can never be mistaken for a new one.

Can the agent use an MCP server instead of an SDK?

Yes. mailcycle-mcp gives any MCP client tools to list, read and wait for mail in an agent's inbox, and Browser Use can call it from a plain @tools.action function. The SDK route in this guide also creates and deletes addresses from code, which suits a task that wants a fresh address every run.

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 that signs in with Mailcycle.sign_in(phrase) can receive on every plan, Free included. See plans and limits.

How do I keep the password out of the model's prompt in Browser Use?

Pass sensitive_data to the Agent, a dictionary of placeholders and values. The task and the model see the placeholder name, such as x_password, and Browser Use fills in the real value when it types, so the password is not part of the prompt.

Receive email in code