April 4, 2026

Write OTP Authentication E2E Tests in 5 Lines with Playwright

PlaywrightE2EOTPTest Automation

The Problem

OTP (One-Time Password) authentication has long been a pain point for E2E testing. Receiving an email, extracting the code from the body, and entering it into a form — automating this entire flow has traditionally been extremely complex.

With MailBrew's @mailbrew/playwright plugin, you can solve this in just 5 lines of code.

Setup

npm install -D @mailbrew/playwright

Add the plugin to your Playwright config:

// playwright.config.js
import { defineConfig } from '@playwright/test';
import { mailbrewPlugin } from '@mailbrew/playwright';

export default defineConfig({
  use: {
    ...mailbrewPlugin({
      apiKey: process.env.MAILBREW_API_KEY,
    }),
  },
});

Writing the Test

import { test, expect } from '@playwright/test';

test('can login with OTP', async ({ page, mailbox }) => {
  // 1. Get a unique test email address (auto-generated)
  const addr = mailbox.address;

  // 2. Enter email in the login form
  await page.goto('https://myapp.com/login');
  await page.fill('[name="email"]', addr);
  await page.click('button[type="submit"]');

  // 3. Capture OTP automatically (waits for email → extracts code)
  const otp = await mailbox.captureOtp();

  // 4. Enter OTP and complete login
  await page.fill('[name="otp"]', otp);
  await page.click('button[type="submit"]');

  // 5. Verify login success
  await expect(page.locator('.dashboard')).toBeVisible();
});

That's it. mailbox.captureOtp() internally:

  1. Waits for incoming email via long-polling
  2. Automatically extracts 4-8 digit OTP codes from the email body
  3. Returns the code as a string

Running in CI

GitHub Actions example:

- name: Run E2E tests
  run: npx playwright test
  env:
    MAILBREW_API_KEY: ${{ secrets.MAILBREW_API_KEY }}

Just set the API key as an environment variable, and the same tests work in CI.

Test Isolation

The Playwright plugin automatically generates a unique email address for each test case. No conflicts even with parallel execution. Addresses are auto-cleaned after tests complete.

Comparison

Traditional Approach MailBrew
Configure IMAP libraries Add plugin in 1 line
Implement email polling captureOtp() in 1 line
Regex to extract OTP Auto-extraction
Email isolation between tests Auto-generated addresses
SMTP setup in CI API key only

If you need to test email auth flows in E2E tests, MailBrew is the simplest option. Get started free.

← Back to blog
© 2026 MailBrew