Menu PHP

SDKs

PHP SDK

The official client of the fake-email.pro API for PHP 8.1 and later, with no Composer dependencies – it sends its requests through ext-curl. It covers every endpoint with typed, readonly models, throws an exception class per error status, retries rate limits on its own, and waits for the email of an end-to-end test – handing back its one-time code or confirmation link. Open source under the MIT license.

PHP 8.1+, no Composer dependencies, on ext-curl; PHPUnit, Pest, Laravel Dusk and Panther

Terminal
composer require --dev fake-email-pro/fake-email-php

fake-email-pro/fake-email-php on PackagistSource on GitHub

API key

Create a key as in Quickstart and put it in the FAKE_EMAIL_API_KEY environment variable – a CI secret on a build agent, or an <env> of phpunit.xml. The client reads it from $_SERVER, $_ENV or getenv() when it is created, so a .env file works too once it is loaded: Symfony's .env.test by the test bootstrap, before any test; Laravel's .env (or .env.dusk.local under Dusk) only when the app boots in parent::setUp(), so a client made in setUpBeforeClass() sees just the process environment and the <env> of phpunit.xml. It also takes the key as new FakeEmail('fep_...'). The API is server-to-server, without CORS: call it from the test process, never from the page under test.

Quickstart

PHP
<?php

require __DIR__ . '/vendor/autoload.php';

use FakeEmailPro\FakeEmail;

$client = new FakeEmail(); // reads FAKE_EMAIL_API_KEY

$mailbox = $client->mailboxes->create();
echo 'Sign up with ', $mailbox->address, PHP_EOL;

try {
    // Long-polls the mailbox for up to 60 s and returns the one-time code
    $code = $client->waitForCode($mailbox->address, subject: 'verification');
    echo $code, PHP_EOL;
} finally {
    $client->mailboxes->delete($mailbox->address);
}

PHPUnit and Laravel Dusk

One client for the test class, created in the first setUp() after Laravel has loaded its .env, a fresh mailbox for every test, removed in tearDown() even when the test fails, and the browser driven by Laravel Dusk. With Symfony Panther it is the same: submit the form, call waitForCode(), type the code. In Pest the mailbox goes into beforeEach() and afterEach().

PHP
<?php

namespace Tests\Browser;

use FakeEmailPro\FakeEmail;
use Laravel\Dusk\Browser;
use Tests\DuskTestCase;

final class SignUpTest extends DuskTestCase
{
    private static ?FakeEmail $client = null;
    private string $inbox;

    // A fresh mailbox for every test, deleted when the test ends
    protected function setUp(): void
    {
        parent::setUp(); // boots Laravel, which loads .env
        // One client for the class, created once the app has booted:
        // FAKE_EMAIL_API_KEY from the environment, phpunit.dusk.xml or Laravel's .env
        self::$client ??= new FakeEmail();
        $this->inbox = self::$client->mailboxes->create()->address;
    }

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

    public function testSignUpWithAnEmailCode(): void
    {
        $this->browse(function (Browser $browser) {
            $browser->visit('/sign-up')
                ->type('email', $this->inbox)
                ->press('Sign up');

            $code = self::$client->waitForCode($this->inbox, subject: 'verification');

            $browser->type('code', $code)
                ->press('Continue')
                ->assertSee('Email confirmed');
        });
    }
}

Waiting for an email

  • waitForMessage($address, ...) – the first message that matches from, subject and an optional match callback, all named arguments. It repeats the 60-second long poll until timeout (60 s by default), then throws a WaitTimeoutException.
  • waitForCode() and waitForLink() – the same, returning the code or the confirmation link the API read out of the email; a message without one is skipped.
  • For the next email in the same mailbox, pass after with the id of the one you have. More on the flow in Email testing.
PHP
use FakeEmailPro\Models\SimpleMessage;

$first = $client->waitForMessage($address, subject: 'Welcome');

// Strictly after the first one: nothing that arrived in between is lost
$second = $client->waitForMessage(
    $address,
    after: $first->id,
    match: fn (SimpleMessage $m) => $m->attachmentsCount > 0,
);

Methods and models

The client groups its methods as $client->mailboxes, ->messages, ->domains and ->limits; optional parameters are named arguments. listAll() returns a generator that fetches page after page as the foreach goes. The models in FakeEmailPro\Models have readonly properties named as in the API: nullable fields are ?string, timestamps are DateTimeImmutable.

The client has a method for each endpoint of the API; their parameters and responses are in Endpoints.

Errors and retries

Every error of the API is thrown as an APIError with the HTTP status, the error code, the message and the rate-limit headers; its subclass names the case: BadRequestError 400, AuthenticationError 401, QuotaExhaustedError 402, PermissionDeniedError 403, NotFoundError 404, ConflictError 409, RateLimitError 429, InternalServerError 5xx. What each status and code means is in Errors. A request that got no response throws APIConnectionError, and one whose HTTP attempt outlasted its timeout APITimeoutError, a subclass of it.

Retries (twice by default) wait the Retry-After of the response, or a short backoff without one. A 429 and a 503 are retried on every method, since the server refused them before doing anything – except a 503 that asks to come back in more than 5 s, which is thrown at once. A network error, a timed-out attempt, a 502, a 504 and Cloudflare's 520–524 are retried on GET and DELETE only, so a mailbox is never created twice; a retried DELETE that gets 404 counts as done, since the attempt before it went through. A wait helper waits out 429, 502–504, 520–524 and connection errors until its own deadline, and then throws WaitTimeoutError.

In PHP the names end in Exception and live in FakeEmailPro\Exception: APIError is ApiException, NotFoundError is NotFoundException, InternalServerError is InternalServerErrorException, and so on, all under FakeEmailException, a RuntimeException; no response at all is an ApiConnectionException, and an HTTP attempt past its timeout an ApiTimeoutException, a subclass of it. The API's error code is $errorCode, since getCode() of a PHP exception is an integer – here, the HTTP status.

PHP
use FakeEmailPro\Exception\ApiException;
use FakeEmailPro\Exception\NotFoundException;

try {
    $mailbox = $client->mailboxes->get($address);
} catch (NotFoundException $e) {
    // expired or deleted: $e->status === 404
} catch (ApiException $e) {
    // any other status: $e->status, $e->errorCode, $e->getMessage()
    error_log($e->getMessage()); // "403 plan_forbidden: ..."
}

Configuration

PHP
use FakeEmailPro\FakeEmail;
use FakeEmailPro\Http\CurlTransport;

$client = new FakeEmail(
    apiKey: 'fep_...',                     // default: FAKE_EMAIL_API_KEY
    baseUrl: 'https://api.fake-email.pro', // default
    timeout: 30.0,                         // seconds per HTTP attempt; a wait request always gets its server timeout + 10 s
    maxRetries: 2,                         // 0 disables retries
    userAgent: 'my-e2e-suite/1.0',         // appended to fake-email-pro-php/<version>
    transport: new CurlTransport([CURLOPT_PROXY => 'http://proxy.internal:3128']), // any extra CURLOPT_*
);

// The same client with other settings, for some calls
$client->withOptions(timeout: 5.0, maxRetries: 0)->domains->list();

The constructor throws FakeEmailException when there is no key. Create the client once and share it between tests: its curl handle keeps the connection alive. withOptions() returns a copy with another timeout or retry count; its timeout does not shorten a wait, since a long poll always gets its server timeout + 10 s. To send requests through your own HTTP stack, implement FakeEmailPro\Http\Transport and pass it as transport.

Other languages

C# / .NET, Go, Java, JavaScript / TypeScript, Python – or every SDK and the OpenAPI document for any other language.

Something missing, confusing or wrong on this page? Tell us