Test Email Flows on Real Devices with Appium: Read Sign-Up Codes in Python

Test sign-up and verification emails on real Android devices with Appium and pytest: an address per test, held by the phone, wait for the email, read the code.

By · · 11 min read

Python code from this guide, in test_signup.py, where an Appium test waits for a Mailcycle email

Appium drives the app on a real phone, and a sign-up test needs one more thing: a real address to type into the app and a way to read what your backend sends back. This tutorial gives each test an address of its own, held by the phone under test, and mail that clears itself. A pytest fixture creates the address and assigns it to the device, the test submits the sign-up screen with it, waits for the code and finishes the flow, and the fixture deletes the address afterwards.

It uses Python with the mailcycle package, the Appium Python client and pytest. Mail is encrypted the moment it arrives, and the package opens it on the machine running the tests.

Quick answer: how to read a verification email in an Appium test

Create an address in a pytest fixture, type it into the sign-up screen, then call mailcycle.messages.wait_for(). It returns the decrypted email, and the test takes the code from message.text.

since = datetime.now(timezone.utc)
driver.find_element(AppiumBy.ID, "com.example.shop:id/email").send_keys(inbox.email_address)
driver.find_element(AppiumBy.ACCESSIBILITY_ID, "Create account").click()

email = mailcycle.messages.wait_for(address_id=inbox.id, subject="verify", since=since, timeout=60)

The rest of this guide builds the fixtures and the full test around that call.

What you’ll build

  • Four pytest fixtures in conftest.py: mailcycle (one signed-in client for the session), lab_device (the phone, found by name), inbox (a new address for each test, assigned to the phone and deleted afterwards) and driver (an Appium session on that phone).
  • An extract_code() helper that pulls a six-digit code out of an email.
  • A test that signs up with the address, reads the code and verifies the account.

The flow is the same in every test: Appium submits the sign-up screen, your backend’s email provider delivers a real email, the test waits for it over the API, and Appium finishes the job. Nothing is stubbed between your app and the inbox, so the test covers your templates, sender settings and provider as they behave on the device build you ship.

Flow: an Appium test signs up on a phone with a fresh address, the backend sends a verification email, Mailcycle receives it encrypted on arrival, and the code is read to finish sign-up
An Appium test signs up on a phone with a Mailcycle address, waits for the verification email and reads the code from it.

Prerequisites

  • A backend that sends real email from the environment you test. Usually staging, sending through your normal provider.
  • An Android device or emulator, and Appium. Appium Server 2 with the UiAutomator2 driver (appium driver install uiautomator2), the Android SDK platform tools, and your app installed on the device.
  • Python 3.10 or later.
  • A Mailcycle account and 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 tests. Create the account in the web app. The free 7-day Scale trial covers a full lab, with no card.
  • The phone paired as a Worker. Install Mailcycle on the phone, choose Worker Device, and claim it from Devices in your account with the QR code or the 8-digit code. Give it a name such as lab-pixel-1. The Pair many devices guide covers a whole stack of phones in one pass.

Step 1: Install the Appium client, pytest and the Mailcycle package

python3 -m venv .venv && source .venv/bin/activate
pip install Appium-Python-Client pytest 'mailcycle[events]==0.8.0'

The events extra adds websockets, so wait_for hears new mail as it arrives; without it, the package checks the address every five seconds. Start the Appium server in another terminal with appium, and check the phone shows up in adb devices.

Step 2: Set the environment

export MAILCYCLE_PHRASE="twelve words of your recovery phrase ..."
export LAB_DEVICE_NAME="lab-pixel-1"
export APP_PACKAGE="com.example.shop"
export APP_ACTIVITY=".MainActivity"
export ANDROID_UDID="emulator-5554"   # from adb devices; leave out for the only device

In CI these become secrets passed to the test step.

Step 3: Write the fixtures

Fixtures are the right place for setup and clean-up in pytest: a test asks for inbox by name, pytest builds it before the test, and runs the code after yield when the test ends, pass or fail. Create conftest.py:

import os
import re
from collections.abc import Iterator

import pytest
from appium import webdriver
from appium.options.android import UiAutomator2Options
from mailcycle import Address, Mailcycle, Message


@pytest.fixture(scope="session")
def mailcycle() -> Iterator[Mailcycle]:
    with Mailcycle.sign_in(os.environ["MAILCYCLE_PHRASE"]) as client:
        yield client


@pytest.fixture(scope="session")
def lab_device(mailcycle: Mailcycle):
    """The phone under test, found by the name it was given in the app."""
    name = os.environ["LAB_DEVICE_NAME"]
    return next(d for d in mailcycle.devices.list() if d.name == name)


@pytest.fixture
def inbox(mailcycle: Mailcycle, lab_device, request: pytest.FixtureRequest) -> Iterator[Address]:
    """A fresh address for one test, held by the phone and deleted afterwards."""
    address = mailcycle.addresses.create(prefix="lab", label=request.node.nodeid, retention_days=1)
    mailcycle.devices.assign(lab_device.id, address.id)
    yield address
    mailcycle.addresses.delete(address.id)


@pytest.fixture
def driver() -> Iterator[webdriver.Remote]:
    options = UiAutomator2Options()
    options.platform_name = "Android"
    if "ANDROID_UDID" in os.environ:  # leave it out for the only connected device
        options.udid = os.environ["ANDROID_UDID"]
    options.app_package = os.environ["APP_PACKAGE"]
    options.app_activity = os.environ["APP_ACTIVITY"]
    options.no_reset = False
    session = webdriver.Remote(os.environ.get("APPIUM_URL", "http://127.0.0.1:4723"), options=options)
    session.implicitly_wait(5)
    yield session
    session.quit()


def extract_code(message: Message, digits: int = 6) -> str:
    match = re.search(rf"code is (\d{{{digits}}})", message.text)
    if match is None:
        raise AssertionError(f"No {digits}-digit code in {message.subject!r}:\n{message.text}")
    return match.group(1)

What each piece does:

  • Mailcycle.sign_in(phrase) signs in with the recovery phrase, as the app does. A session can create addresses, open their mail and hand an address to a device.
  • devices.list() returns the account’s devices. Their names are sealed, so they are opened here with the phrase.
  • addresses.create(prefix="lab") returns an address like lab-x7k2@...: your prefix plus a random ending. The label is sealed with the address and records which test it was for. retention_days=1 clears any mail the clean-up misses after a day, not the default seven.
  • devices.assign(device_id, address_id) gives the phone the address and hands it the keys, so the address also shows in the Mailcycle app on that phone.
  • addresses.delete() removes the address and its mail. A deleted address is retired and never issued to anyone again.
  • extract_code() anchors on the words around the code, so order numbers and dates that also have six digits are skipped. Change the pattern to match your email.

Step 4: Write the test

Create test_signup.py. Change the element ids, accessibility labels and texts to match your app (Appium Inspector shows each element’s id and content-desc):

import os
from datetime import datetime, timezone

from appium.webdriver.common.appiumby import AppiumBy
from mailcycle import Address, Mailcycle
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

from conftest import extract_code

PKG = os.environ.get("APP_PACKAGE", "com.example.shop")


def test_signup_code_verifies_account(driver, inbox: Address, mailcycle: Mailcycle) -> None:
    wait = WebDriverWait(driver, 15)
    since = datetime.now(timezone.utc)

    driver.find_element(AppiumBy.ID, f"{PKG}:id/email").send_keys(inbox.email_address)
    driver.find_element(AppiumBy.ACCESSIBILITY_ID, "Create account").click()
    wait.until(EC.presence_of_element_located((AppiumBy.XPATH, '//*[contains(@text, "Check your email")]')))

    email = mailcycle.messages.wait_for(address_id=inbox.id, subject="verify", since=since, timeout=60)
    driver.find_element(AppiumBy.ID, f"{PKG}:id/code").send_keys(extract_code(email))
    driver.find_element(AppiumBy.ACCESSIBILITY_ID, "Verify").click()

    welcome = wait.until(EC.presence_of_element_located((AppiumBy.ID, f"{PKG}:id/welcome")))
    assert welcome.text == "Welcome"

Run it with pytest. Three details keep it reliable:

  • Take since before the tap that sends the email. wait_for counts mail received from since onwards, including mail that landed before the listener was up, so a fast backend cannot beat the test to it. Pass a timezone-aware datetime.
  • Use subject to pick the email. It is a case-insensitive “contains”, so "verify" matches “Verify your email” and “Please verify your account”. from_address works the same way on the sender.
  • Wait for the screen, then for the mail. The explicit wait on the “Check your email” text confirms the app submitted the form before the test starts listening for the message.

An address per test keeps tests independent

The inbox fixture creates the address before each test and deletes it afterwards, even when the test fails. A rerun gets a new address and a new email, never the last attempt’s spent code, so reruns and parallel runs on other phones do not interfere. Each test’s email arrives in an inbox only that test can read, and retention_days=1 clears anything left over the next day.

A lab of phones

The same suite runs on every phone in the lab. Pair each one as a Worker with its own name, then run one pytest process per phone with a different LAB_DEVICE_NAME and ANDROID_UDID (and an Appium server on its own port, set with APPIUM_URL). Each process looks up its own phone and gives it its own addresses, so the phones never share an inbox. Devices stay in Devices in your account after the run; remove one when it leaves the lab. Email for a device fleet covers pairing, tagging and grouping a whole lab from one account.

The same fixtures cover a magic link or a reset link: request the email, wait for it with wait_for, take the first link from email.text that points at your app’s host, and open it on the phone with driver.get(link) or mobile: deepLink for an app link. Seed the user through your own test API first, so the reset test does not depend on the sign-up test.

Most mobile sign-up emails carry a link that should open the app, not a browser. With a real inbox the test already holds the link as text, so it can hand it straight to the device. On Android, the UiAutomator2 driver has a mobile: deepLink command that opens a URL and names the package that should handle it.

link = re.search(r"https://app\.example\.com/verify\?\S+", email.text).group(0)
driver.execute_script("mobile: deepLink", {"url": link, "package": PKG})
wait.until(EC.presence_of_element_located((AppiumBy.ID, f"{PKG}:id/welcome")))

This exercises the part of the flow that is easiest to break on a phone: the app link configuration. If the link opens the browser instead of the app, the test fails on the welcome screen, which is the failure a customer would meet. Run the same test once with the app installed and once with it removed if you also care about the fallback to the store page.

Reset the app between tests

Each test should start from a known state, with no signed-in user left over. Appium offers two ways. Setting no_reset to False, as the fixture does, resets app data when the session starts. For a faster suite that reuses one session, terminate and restart the app between tests:

@pytest.fixture(autouse=True)
def fresh_app(driver):
    driver.terminate_app(PKG)
    driver.activate_app(PKG)

Pair this with the per-test address and you get a clean user, a clean app and a clean inbox for every test, which is what makes a phone suite stable enough to run overnight.

The same test on iOS

Appium runs iOS through the XCUITest driver, and the email half of the test does not change at all. Only the session options and the locators do.

from appium.options.ios import XCUITestOptions

options = XCUITestOptions()
options.platform_name = "iOS"
options.bundle_id = os.environ["BUNDLE_ID"]
options.udid = os.environ["IOS_UDID"]

Use accessibility ids for locators, because Appium maps the same AppiumBy.ACCESSIBILITY_ID to the Android content-desc and the iOS accessibilityIdentifier. One test file can then serve both platforms, with a fixture that builds the right options from an environment variable. Pair the iPhone as a Worker the same way as an Android phone.

Hybrid apps and web views

If your sign-up screen is a web view inside the app, Appium exposes it as a separate context. List driver.contexts, switch to the one that starts with WEBVIEW, fill the form with ordinary web locators, then switch back to NATIVE_APP for the rest. The email step does not care which context is active, because it never touches the screen. Keep the since timestamp before the submit tap in either context.

Run on a cloud device provider

The fixtures talk to whatever Appium endpoint APPIUM_URL names, so the same suite runs on a device cloud as well as a rack on your desk. Point APPIUM_URL at the provider’s hub, add the provider’s capabilities to the options, and keep the mail code as it is. The test process reads the email from wherever it runs, and the phone in the cloud only needs a route to your staging backend. You can still pair a local phone as a Worker for the days you want to watch a run on the device itself.

Which Mailcycle plan for a device lab

Signing in with the recovery phrase and receiving mail works on every plan, and every paid plan pairs as many Workers as you need. A lab that runs a suite per phone fits Scale at $19 a month, with 1,000 addresses and 750,000 messages received a month, so each phone can hold many addresses. Fleet at $99 a month has 10,000 addresses for a large lab. See pricing and the fleet solutions page.

What to assert on a phone

A real inbox lets a mobile test check more than the code:

  • The email arrives once. List the address’s messages after sign-up and assert exactly one verification email, so a retry bug that double sends is caught.
  • The deep link opens the app. Assert the welcome screen is visible after mobile: deepLink, as above.
  • The sender and subject match your brand. A wrong sender name is a common release bug, and one assert catches it.
  • The email renders its text. Because the test reads email.text, a template that ships an empty plain text part fails the code extraction, which is worth knowing before a customer sees it.

Capture the screen and logcat when a test fails

A failing phone test is much easier to read with evidence. Appium can take a screenshot and read the device log, and the email you waited for tells you whether the backend or the app was at fault. Add a hook that saves both on failure:

@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    if outcome.get_result().failed and "driver" in item.fixturenames:
        d = item.funcargs["driver"]
        d.get_screenshot_as_file(f"artifacts/{item.name}.png")
        with open(f"artifacts/{item.name}.log", "w") as f:
            f.write("\n".join(e["message"] for e in d.get_log("logcat")[-200:]))

If the test timed out waiting for the email, check the screen first. A screenshot that still shows the sign-up form means the tap did not submit, and a screenshot of “Check your email” means the backend never sent the message, so look at your provider’s logs. The last 200 logcat lines usually show a network error from the app when the request failed.

Emulator or real device

An emulator is quick and cheap for the daily run: it starts in seconds, resets cleanly and runs in CI. A real phone covers what an emulator cannot, such as the vendor’s keyboard, battery rules and the way the system handles app links. A good split is the emulator on every commit and the paired phones in the lab overnight, both running the same pytest file against the same staging backend. The mail is read through the API in both cases, so the only code that differs is the Appium session options. Keep one fixture that picks the options from an environment variable such as TARGET=emulator or TARGET=lab, so a developer can reproduce an overnight failure on a laptop with a single flag and the same test file. Record the target and the device name in the test report, so a failure on one phone model is easy to tell apart from a failure everywhere.

Troubleshooting

wait_for raises a timeout. No matching email arrived in time. Check, in order: that the backend really sent it (your provider’s logs), that the subject filter matches the real subject, and that staging can send to outside addresses. Some providers limit new or sandboxed accounts to recipients you have verified; Amazon SES’s sandbox is one example.

StopIteration in lab_device. No device has that name. Open Devices in the app, check the name, and check the phone finished pairing.

The test taps before the screen has changed. Submitting a form takes a moment, so use an explicit wait (WebDriverWait with expected_conditions) rather than reading the screen straight away.

It found an older email. On an address a test reuses, take since right before the tap that sends, and delete read emails. With a new address per test, as here, an older email cannot match.

extract_code picks the wrong number. Order numbers and dates can also have six digits. Anchor the pattern on the text around the code and use the capture group, as the helper does.

The session does not start. Check adb devices lists the phone, the Appium server is running, APP_PACKAGE and APP_ACTIVITY match your build, and the UiAutomator2 driver is installed.

Next steps

FAQ

How do I test email verification in a mobile app with Appium?

Give the test a real address, type it into your app's sign-up screen with Appium, then wait for the email in code and finish the flow. With Mailcycle, a pytest fixture creates an address with mailcycle.addresses.create() and assigns it to the phone, the test calls mailcycle.messages.wait_for(address_id=..., since=..., subject=...), takes the code from message.text, and the fixture deletes the address afterwards.

Can Appium read emails by itself?

No. Appium drives the app on the device, so the email has to be read by your own code through an API or a mail protocol. A test inbox API returns parsed messages, which is simpler than opening a mail app on the phone and scraping it.

How do I get the OTP code from an email in an Appium test?

Wait for the message, then match the code in its plain-text body, for example re.search(r"code is (\d{6})", message.text). Anchoring the pattern on the words around the code avoids picking up other six-digit numbers in the email.

What does it mean to pair a phone as a Worker?

A Worker is a device connected to your Mailcycle account that receives inboxes. You install the Mailcycle app on the phone, choose Worker Device, and claim it from your account with a QR code or an 8-digit code. Pairing one phone is available on every plan, and every paid plan pairs as many as you need. See Pair many devices.

Do I need a real device, or does an emulator work?

Both work. The test reads the email through the API, so the same code runs against an emulator on your laptop and a phone in a rack. Pair whichever you test on as a Worker if you want its addresses to show in the Mailcycle app on it.

Which Mailcycle plan do I need for email tests?

Signing in with the recovery phrase and receiving mail works on every plan, Free included. Running a suite with an address per test is simplest on a paid plan. See plans and limits.

Can I use the same test on iOS with Appium?

Yes. The email half is the same, because the test reads the message through the API. Swap the capabilities for the XCUITest driver (platformName iOS, automationName XCUITest and your app's bundleId), and change the locators to accessibility ids, which both platforms can share.

Receive email in code