# Pytest email and OTP testing

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

```bash
pip install mailslurp-client
```

## Create an inbox with the Python SDK

```python
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

```python
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

<div data-component="DocsExamplesList" class="docs-card-grid docs-examples-list" data-example-terms="pytest" data-example-count="1">
<a class="docs-card docs-example-card" href="https://www.github.com/mailslurp/examples/tree/master/python2-pytest" target="_blank" rel="noopener noreferrer"><span class="docs-card-title">Python2 Pytest</span><span class="docs-card-description">python2 example repository: <code>python2-pytest</code></span></a>
</div>

## Related docs

- [Python SDK](/docs/python/)
- [Wait for methods](/docs/wait-for/)
- [Integration testing guide](/docs/testing/)
