# Testing Emails with Selenium

Use Selenium, pytest and the Python SDK to sign up with a fresh address, wait for the email and drive the browser to its code or link.

To test an email with Selenium, create an address with `receiver.inboxes.create()`, type it into your form with `send_keys()`, then call `wait_for_otp()` or `wait_for()` with `since=inbox.created_at`. The wait returns as soon as the email arrives, with the code and links already extracted, so the test types the code or opens the link with `driver.get()` in the same browser session.

## Install

```bash
pip install receiverdotemail selenium pytest pytest-asyncio
export RECEIVER_API_KEY=recv_live_...   # a project API key
```

Selenium 4.6 and later download the matching browser driver themselves, but an old `chromedriver` on your `PATH` takes precedence: remove it if Chrome refuses to start. The Python SDK is async, so the tests are `async def` functions run by pytest-asyncio; Selenium's calls are ordinary blocking calls inside them.

```ini
[pytest]
asyncio_mode = auto
asyncio_default_fixture_loop_scope = function
```

## Fixtures

```python
import pytest
from selenium import webdriver
from receiverdotemail import ReceiverClient

@pytest.fixture
async def receiver():
    async with ReceiverClient() as client:  # reads RECEIVER_API_KEY
        yield client

@pytest.fixture
async def inbox(receiver):
    """A fresh address for every test."""
    return await receiver.inboxes.create(prefix="selenium")

@pytest.fixture
def driver():
    options = webdriver.ChromeOptions()
    options.add_argument("--headless=new")
    driver = webdriver.Chrome(options=options)
    driver.implicitly_wait(5)
    yield driver
    driver.quit()
```

The API appends six random characters to the prefix, so every test, and every pytest-xdist worker, gets an address no other test uses.

## Sign Up and Enter the Code

```python
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

BASE_URL = "http://localhost:3000"

async def test_sign_up_with_emailed_code(driver, receiver, inbox):
    driver.get(f"{BASE_URL}/signup")
    driver.find_element(By.NAME, "email").send_keys(inbox.address)
    driver.find_element(By.CSS_SELECTOR, "button[type=submit]").click()

    otp = await receiver.emails.wait_for_otp(
        recipient=inbox.address,
        since=inbox.created_at,
        code_length=6,
        timeout=60,  # seconds
    )

    driver.find_element(By.NAME, "code").send_keys(otp.code)
    driver.find_element(By.CSS_SELECTOR, "button[type=submit]").click()
    WebDriverWait(driver, 10).until(EC.url_contains("/welcome"))
```

`wait_for_otp()` raises `ReceiverTimeoutError` when no code arrives in time; its `since` and `waited_seconds` say what it waited for. `otp.candidates` lists every code it found, newest first, if you need to choose.

## Open the Link in the Same Browser

`email.links` holds every URL in the email, plain-text body first and then the HTML links. Pick the one you want by path and open it with `driver.get()`, which keeps the cookies from sign-up:

```python
import html
import re
from urllib.parse import urlsplit

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait

BASE_URL = "http://localhost:3000"

def find_link(links, path):
    """The first link to path, without the &amp; and trailing punctuation emails add."""
    for raw in links:
        link = re.sub(r"[.,;:!?)]+$", "", html.unescape(raw))
        if urlsplit(link).path.startswith(path):
            return link
    raise AssertionError(f"no {path} link in {links}")

async def test_confirmation_link(driver, receiver, inbox):
    driver.get(f"{BASE_URL}/signup")
    driver.find_element(By.NAME, "email").send_keys(inbox.address)
    driver.find_element(By.CSS_SELECTOR, "button[type=submit]").click()

    email = await receiver.emails.wait_for(
        recipient=inbox.address,
        since=inbox.created_at,
        subject="Confirm",  # case-insensitive substring
        timeout=60,
    )

    driver.get(find_link(email.links, "/confirm"))
    WebDriverWait(driver, 10).until(EC.url_contains("/dashboard"))
```

[Testing Magic-Link Login](https://www.receiver.email/docs/guides/magic-links) explains why the helper cleans each link, and what to do about tracking redirects and one-time links.

## If Your Suite Is Synchronous

To keep plain `def` tests, replace the async fixtures with one that runs the SDK on a private event loop for the whole session, using `asyncio.Runner` (Python 3.11 and later). Don't call `asyncio.run()` for each request: the client's connections belong to the loop that opened them.

```python
import asyncio

import pytest
from receiverdotemail import ReceiverClient

@pytest.fixture(scope="session")
def mail():
    """(run, client): run(coroutine) returns its result on the session's loop."""
    with asyncio.Runner() as runner:
        client = ReceiverClient()
        yield runner.run, client
        runner.run(client.close())
```

```python
# Imports and BASE_URL as in test_signup.py
def test_sign_up_with_emailed_code(driver, mail):
    run, receiver = mail
    inbox = run(receiver.inboxes.create(prefix="selenium"))
    driver.get(f"{BASE_URL}/signup")
    driver.find_element(By.NAME, "email").send_keys(inbox.address)
    driver.find_element(By.CSS_SELECTOR, "button[type=submit]").click()

    otp = run(receiver.emails.wait_for_otp(
        recipient=inbox.address, since=inbox.created_at, code_length=6, timeout=60
    ))
    driver.find_element(By.NAME, "code").send_keys(otp.code)
```

## Parallel Runs and CI

- **Parallel**: `pytest -n 4` with pytest-xdist needs no changes, since each test waits on its own address.
- **Fewer requests**: each test resolves its project once with `whoami()`. Set `RECEIVER_PROJECT_ID` to skip that, which helps on the Free plan's 10 requests per minute.
- **CI**: GitHub's Ubuntu runners have Chrome installed, so the headless fixture runs as it is. Pass `RECEIVER_API_KEY` from your secrets; [CI/CD Integration](https://www.receiver.email/docs/guides/ci-cd) has full workflows.

## Next Steps

- [Pytest Integration](https://www.receiver.email/docs/guides/pytest): more fixtures and API-level email tests
- [Testing Sign-Up Email Verification](https://www.receiver.email/docs/guides/email-verification): what to assert beyond the happy path
- [Python SDK](https://www.receiver.email/docs/sdks/python): every method and option

---

Source: https://www.receiver.email/docs/guides/selenium
