MailSlurp logo

Pytest email and OTP testing

Use MailSlurp in Pytest suites to create inboxes, wait for verification emails, and extract OTP codes.

View Markdown Agent setup

Pytest works well with MailSlurp when your test suite already drives the browser, API, or service under test and the MailSlurp Python client handles inbox state beside it. The usual pattern is to create an inbox in the test, pass inbox.email_address into the workflow, wait for the email, and extract the OTP for the next assertion.

Install

pip install mailslurp-client

Create an inbox with the Python SDK

inbox_controller = mailslurp_client.InboxControllerApi(api_client)
inbox = inbox_controller.create_inbox()
assert "@mailslurp" in inbox.email_address
begin_signup_with_email_address(inbox.email_address)

Example Pytest OTP flow

import os
import re

import mailslurp_client
from mailslurp_client import ApiClient, Configuration, InboxControllerApi, WaitForControllerApi


configuration = Configuration()
configuration.api_key["x-api-key"] = os.environ["API_KEY"]


def test_receives_and_extracts_email_otp():
    with ApiClient(configuration) as api_client:
        inbox_controller = InboxControllerApi(api_client)
        wait_for_controller = WaitForControllerApi(api_client)

        inbox = inbox_controller.create_inbox_with_defaults()

        # Submit inbox.email_address in the app under test here.
        # In browser suites this usually happens inside a Playwright or Selenium fixture.

        email = wait_for_controller.wait_for_latest_email(
            inbox_id=inbox.id,
            timeout=120000,
            unread_only=True,
        )

        assert email.body is not None
        otp = re.search(
            r"(?:verification code|OTP|code)[:\\s-]*(\\d{6})",
            email.body,
        ).group(1)

        assert otp

Example projects