MailSlurp logo

PHPUnit email and OTP testing

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

View Markdown Agent setup

MailSlurp fits PHPUnit when your PHP test suite drives application requests, browser helpers, or Laravel feature tests and the MailSlurp PHP client handles disposable inboxes and wait methods. This keeps email verification and password-reset checks inside the same assertions you already run in CI.

Install

composer require --dev mailslurp/mailslurp-client-php

Create an inbox with the PHP SDK

$options = new \MailSlurp\Models\CreateInboxDto();
$options->setName("Test inbox");
$options->setPrefix("test");
$inbox = $inboxController->createInboxWithOptions($options);

Example PHPUnit OTP flow

<?php

use MailSlurp\Apis\InboxControllerApi;
use MailSlurp\Apis\WaitForControllerApi;
use MailSlurp\Configuration;
use PHPUnit\Framework\TestCase;

final class SignupOtpTest extends TestCase
{
    public function testCanExtractVerificationCode(): void
    {
        $config = Configuration::getDefaultConfiguration()
            ->setApiKey('x-api-key', getenv("API_KEY"));

        $inboxController = new InboxControllerApi(null, $config);
        $waitForController = new WaitForControllerApi(null, $config);

        $inbox = $inboxController->createInboxWithDefaults();

        // Submit $inbox->getEmailAddress() in the app under test here.

        $email = $waitForController->waitForLatestEmail(
            $inbox->getId(),
            120000,
            true
        );

        preg_match(
            '/(?:verification code|OTP|code)[:\\s-]*(\\d{6})/',
            $email->getBody() ?? '',
            $matches
        );

        $this->assertArrayHasKey(1, $matches);
        $this->assertNotEmpty($matches[1]);
    }
}

Example projects