AssertInbox

Test Laravel email verification with PHPUnit and a real inbox

Laravel's MustVerifyEmail contract sends a signed verification link after registration. Most tests replace the mailer with Mail::fake(), which proves that a notification was queued but not that a message is delivered, that its signed link validates, or that the link points at the right host. This guide adds one PHPUnit feature test that does the whole trip: it registers a user with a unique address, lets Laravel send the email through a real SMTP transport, reads it with AssertInbox, opens the signed link and asserts that email_verified_at is set.

What the test needs from your app

The app must use the MustVerifyEmail contract on the User model and the standard verification routes, which the Laravel starter kits provide: a /register route that signs the new user in, and a signed /verify-email/{id}/{hash} route behind the auth and signed middleware. In .env.testing, set MAIL_MAILER=smtp with the host, port and credentials of a transactional mail service you control, and set APP_URL to the URL the test uses. Do not call Mail::fake() in this test. Check the option names for your Laravel version in the Laravel documentation.

How it works

Mail sent to <namespace>.<tag>@assertinbox.com is stored for your key. GET /v1/wait long-polls for up to 25 seconds and returns the newest matching message as JSON, including id, subject, links and magic_link. Messages are deleted after 24 hours. Each test uses its own tag, so parallel test processes never read each other's mail.

Get an API key

Get one in a click at /start, or with the request below. One request creates a key and your private namespace. No email address or card is needed. The key is shown once, so store it in your CI secrets.

curl -s -X POST https://assertinbox.com/v1/keys
# {"api_key":"ai_...","namespace":"k3x9a1bz","address_template":"k3x9a1bz.<tag>@assertinbox.com"}

Put both values in .env.testing as ASSERTINBOX_KEY (the api_key) and ASSERTINBOX_NAMESPACE (the namespace). If the call returns 403 signups_closed, the beta is not open for new keys. Use inboxes only for services you own or control; see the terms. Limits and error codes are listed in the limits page.

The helper

Save this as tests/Support/Inbox.php. It uses Laravel's Http client, so no extra package is needed. waitForEmail retries on a 408 timeout and accepts the wait filters, and delete removes the messages for a tag.

<?php

namespace Tests\Support;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use RuntimeException;

class Inbox
{
    private const API = 'https://assertinbox.com';

    public readonly string $tag;

    public function __construct(string $prefix = 'laravel')
    {
        $this->tag = strtolower($prefix . '-' . time() . '-' . Str::lower(Str::random(6)));
    }

    public function email(): string
    {
        return env('ASSERTINBOX_NAMESPACE') . '.' . $this->tag . '@assertinbox.com';
    }

    private function client()
    {
        return Http::withToken(env('ASSERTINBOX_KEY'))->timeout(35);
    }

    public function waitForEmail(array $filters = []): array
    {
        $query = array_merge(['tag' => $this->tag, 'timeout' => 25], $filters);
        for ($attempt = 0; $attempt < 3; $attempt++) {
            $response = $this->client()->get(self::API . '/v1/wait', $query);
            if ($response->status() === 200) {
                return $response->json();
            }
            if ($response->status() !== 408) {
                throw new RuntimeException('AssertInbox returned HTTP ' . $response->status());
            }
        }
        throw new RuntimeException('No matching email arrived for tag ' . $this->tag);
    }

    public function delete(): void
    {
        $this->client()->delete(self::API . '/v1/messages', ['tag' => $this->tag]);
    }
}

The feature test

Save this as tests/Feature/EmailVerificationTest.php. It registers through the real route, so the notification goes out over SMTP. Adjust the form fields to match your registration request.

<?php

namespace Tests\Feature;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\Support\Inbox;
use Tests\TestCase;

class EmailVerificationTest extends TestCase
{
    use RefreshDatabase;

    private Inbox $inbox;

    protected function setUp(): void
    {
        parent::setUp();
        $this->inbox = new Inbox('verify');
    }

    protected function tearDown(): void
    {
        $this->inbox->delete();
        parent::tearDown();
    }

    public function test_the_emailed_link_verifies_the_user(): void
    {
        $this->post('/register', [
            'name' => 'Test User',
            'email' => $this->inbox->email(),
            'password' => 'correct-horse-battery',
            'password_confirmation' => 'correct-horse-battery',
        ])->assertRedirect();

        $user = User::where('email', $this->inbox->email())->firstOrFail();
        $this->assertFalse($user->hasVerifiedEmail());

        $mail = $this->inbox->waitForEmail(['subject' => 'verify']);
        $this->assertNotEmpty($mail['magic_link']);
        $this->assertSame(parse_url(config('app.url'), PHP_URL_HOST), parse_url($mail['magic_link'], PHP_URL_HOST));

        $this->get($mail['magic_link'])->assertRedirect();

        $this->assertTrue($user->fresh()->hasVerifiedEmail());
    }

    public function test_a_tampered_link_does_not_verify_the_user(): void
    {
        $this->post('/register', [
            'name' => 'Test User',
            'email' => $this->inbox->email(),
            'password' => 'correct-horse-battery',
            'password_confirmation' => 'correct-horse-battery',
        ]);

        $mail = $this->inbox->waitForEmail(['subject' => 'verify']);
        $this->get($mail['magic_link'] . 'x')->assertForbidden();

        $user = User::where('email', $this->inbox->email())->firstOrFail();
        $this->assertFalse($user->hasVerifiedEmail());
    }
}

Run it with php artisan test --filter EmailVerificationTest. The host assertion comes before the request for the link: a signed URL is valid only for the host it was generated for, and an APP_URL that differs from the address the test requests makes the signature check fail.

Why a signed link needs a real mail

The signature covers the full URL, including the host and the expiry. With a faked mailer the test can build a link itself and will always pass. With a real message the link is exactly what a user receives, so a wrong APP_URL, a proxy that rewrites the scheme or a template that drops the query string all show up here. The second test confirms the opposite direction: a link whose signature has been changed is refused.

Troubleshooting

Next steps

Read Reliable email tests for unique tags, retries and cleanup. Related guides: Django allauth and Rails Devise. The wait filters are described in the docs, and the API reference lists every endpoint.

Free beta, run by AI agents

This service is in free beta and is operated by AI agents under human supervision. Messages are deleted after 24 hours.