fake-email-pro / fake-email-php
Official PHP client for the fake-email.pro API: disposable mailboxes, one-time codes and magic links for end-to-end tests of signup and OTP flows
Requires
- php: >=8.1
- ext-curl: *
- ext-json: *
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.64
- phpstan/phpstan: ^2.1
- phpstan/phpstan-phpunit: ^2.0
- phpunit/phpunit: ^10.5 || ^11.5
- symfony/yaml: ^6.4 || ^7.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
The official PHP client for the fake-email.pro API: create a disposable mailbox, wait for the email, get the one-time code or the magic link. Built for end-to-end tests of signup, OTP and password-reset flows with PHPUnit, Pest, Laravel Dusk and Symfony Panther.
$mailbox = $mail->mailboxes->create(); // ...sign up with $mailbox->address in your app... $code = $mail->waitForCode($mailbox->address); // "048213"
- PHP 8.1+, no Composer dependencies (ext-curl and ext-json)
- Long-poll waiting: the message is returned within about a second of delivery, no polling loops in your tests
- Codes and confirm links are extracted on the server
- Retries on rate limits and transient errors, honoring
Retry-After - An exception class per error status; typed models with readonly properties, checked by PHPStan at level max
API reference: api.fake-email.pro/docs · Guides: fake-email.pro/api/docs/sdks/php
Install
composer require --dev fake-email-pro/fake-email-php
Drop --dev if you use it outside tests.
Get an API key
- Sign in at fake-email.pro. Any account can use the API, the free plan included.
- Open Settings → API keys (fake-email.pro/settings/api-keys) and
create a key. It starts with
fep_and is shown only once. - Put it in the environment of your tests (and in your CI secrets):
export FAKE_EMAIL_API_KEY=fep_...
The client reads FAKE_EMAIL_API_KEY from $_SERVER, $_ENV or getenv(), so a .env.test loaded by Symfony
Dotenv or Laravel works too. A bigger monthly quota and higher limits come with
PRO.
Server-side only. Never put the key in front-end code: anyone could read it, and the API does not allow cross-origin requests (no CORS).
Quickstart
<?php require __DIR__ . '/vendor/autoload.php'; use FakeEmailPro\FakeEmail; $mail = new FakeEmail(); // or new FakeEmail('fep_...') // 1. A fresh address, valid for 24 hours $mailbox = $mail->mailboxes->create(); try { // 2. Make your app send an email to it file_get_contents('https://your-app.example/signup', false, stream_context_create(['http' => [ 'method' => 'POST', 'header' => 'Content-Type: application/x-www-form-urlencoded', 'content' => http_build_query(['email' => $mailbox->address]), ]])); // 3. Wait for the email and take the code $code = $mail->waitForCode($mailbox->address, timeout: 60); echo $code, PHP_EOL; // Or the confirm / magic link // $link = $mail->waitForLink($mailbox->address); } finally { $mail->mailboxes->delete($mailbox->address); }
waitForCode() returns the code found in the email when it was delivered. If none was found then, it reads the
full message and takes its first code; an email with no code at all is skipped and the wait goes on.
waitForLink() does the same with the confirm link.
PHPUnit
A fresh mailbox per test, deleted when the test ends:
use FakeEmailPro\FakeEmail; use PHPUnit\Framework\TestCase; final class SignupTest extends TestCase { private static FakeEmail $mail; private string $inbox; public static function setUpBeforeClass(): void { self::$mail = new FakeEmail(); // FAKE_EMAIL_API_KEY from the environment (or phpunit.xml <env>) } protected function setUp(): void { $this->inbox = self::$mail->mailboxes->create()->address; } protected function tearDown(): void { self::$mail->mailboxes->delete($this->inbox); } public function testSignupSendsACode(): void { $this->signUp($this->inbox); // your app under test $code = self::$mail->waitForCode($this->inbox, subject: 'verification'); $this->confirm($this->inbox, $code); } }
With Pest, the same goes into beforeEach() / afterEach().
Laravel Dusk and Symfony Panther
The browser fills the form, the client waits for the email:
// Laravel Dusk public function testSignUpWithAnEmailCode(): void { $this->browse(function (Browser $browser) { $browser->visit('/signup') ->type('email', $this->inbox) ->press('Send code'); $code = self::$mail->waitForCode($this->inbox, subject: 'verification'); $browser->type('code', $code) ->press('Continue') ->assertSee('Welcome'); }); }
// Symfony Panther public function testSignUpWithAnEmailCode(): void { $client = static::createPantherClient(); $client->request('GET', '/signup'); $client->submitForm('Send code', ['email' => $this->inbox]); $code = self::$mail->waitForCode($this->inbox, subject: 'verification'); $client->submitForm('Continue', ['code' => $code]); $this->assertSelectorTextContains('h1', 'Welcome'); }
Waiting for messages
use FakeEmailPro\Models\SimpleMessage; $message = $mail->waitForMessage( $address, timeout: 60, // seconds, client-side deadline, then WaitTimeoutException from: 'acme.example', // case-insensitive substring of the sender address subject: 'verify', // case-insensitive substring of the subject match: fn (SimpleMessage $m) => $m->attachmentsCount > 0, // any extra check ); $message->code; // "048213" or null $message->confirmLink; // "https://..." or null
from and subject are filtered on the server. A message that fails match is skipped and the wait continues
with the next one. Under the hood the client repeats the server's long poll (up to 60 s each) until the deadline.
The next message
Without after, the wait returns the earliest message in the mailbox, even one that arrived before you
started waiting, so nothing is lost. To wait for a newer one, for example after "Resend code", pass the previous
message's id:
$first = $mail->waitForMessage($address); // ...click "Resend code"... $second = $mail->waitForMessage($address, after: $first->id);
after also takes a DateTimeInterface (or an RFC 3339 string): "messages that arrived after this moment" by the
server's clock. Prefer a message id: it is exact, while a time depends on clock skew. Do not pass a message's
createdAt: a second message in the same millisecond would be skipped.
An after id that is no longer in the mailbox (you deleted that message) is a NotFoundException: if your tests
delete processed messages, wait without after. While the loop runs, it moves after past each message it skips
(one failing match, or without a code or link); if such a message disappears meanwhile, the loop goes on after its
delivery time instead.
Messages, attachments and raw EML
$page = $mail->messages->list($address, page: 0, size: 20); // newest first: $page->content, $page->totalPages foreach ($mail->messages->listAll($address) as $message) { // every page, fetched as the loop goes echo $message->id, ' ', $message->createdAt->format(DATE_ATOM), PHP_EOL; } $full = $mail->messages->get($address, $message->id); $full->html; $full->text; $full->codes; $full->links; $full->attachments; $attachment = $mail->messages->attachment($address, $message->id, $full->attachments[0]->id); // The sender chose the name (the attachment id if they gave none): keep only its last part $name = basename((string) $attachment->fileName); file_put_contents(__DIR__ . '/downloads/' . (\in_array($name, ['', '.', '..'], true) ? 'attachment.bin' : $name), $attachment->data); $attachment->contentType; // "application/pdf" $eml = $mail->messages->raw($address, $message->id); // string, the message as received $mail->messages->delete($address, $message->id);
One long poll without the client-side loop: $mail->messages->wait($address, timeout: 30, after: $id) returns the
message, or null when the server timeout passed (204). timeout is 1..60 seconds (server default 30): 0 or less
throws FakeEmailException before sending, over 60 is a BadRequestException from the server.
Mailboxes, domains and limits
$mail->mailboxes->create(); // random address on a random domain $mail->mailboxes->create(domain: 'example.org'); // random address on that domain $mail->mailboxes->create(localPart: 'signup-test', domain: 'example.org'); // that address (lowercased) $mail->mailboxes->get($address); $mail->mailboxes->list(page: 0, size: 50); foreach ($mail->mailboxes->listAll() as $mailbox) { /* ... */ } $mail->mailboxes->delete($address); // messages are erased; the address is never issued again $domains = $mail->domains->list(); // [Domain{name: 'example.org', type: 'PUBLIC'}, ...] $limits = $mail->limits->get(); // ->quota, ->requestsPerMinute, ->concurrentWaits, ->storage, ->mailboxTtlSeconds
A mailbox accepts mail for 24 hours and cannot be renewed; after that it answers 404. Each created mailbox
spends one unit of your monthly quota (deleting it does not give it back). Custom local parts depend on the plan.
Models live in FakeEmailPro\Models and have readonly properties named as in the API. Nullable fields are
?string / ?Sender, timestamps are DateTimeImmutable. Enum fields are plain strings with the known values as
constants (BodyState::STORED, DomainType::PUBLIC, ErrorCode::NOT_FOUND): a value added by a newer server
passes through as is.
Errors
Every exception the client throws extends FakeEmailPro\Exception\FakeEmailException (a RuntimeException).
Errors from the server are ApiException with $status, $errorCode (the API's error field), $body,
$headers and $rateLimit; statuses with their own meaning have their own subclass:
| Class | When |
|---|---|
BadRequestException |
400 bad_request: an invalid parameter or body |
AuthenticationException |
401 unauthorized: missing, unknown, revoked or expired key |
QuotaExhaustedException |
402 quota_exhausted: monthly mailbox quota spent ($limit, $used, $resetsAt, $upgradeUrl) |
PermissionDeniedException |
403 plan_forbidden: the plan does not allow this |
NotFoundException |
404 not_found: mailbox expired, deleted or not yours; no such message; create(domain: ...) with an unknown or unavailable domain; after names a message that is gone |
ConflictException |
409 address_taken: the address was issued before |
RateLimitException |
429: $errorCode is rate_limit_exceeded or too_many_waits; $retryAfter |
InternalServerErrorException |
5xx |
ApiException |
any other non-2xx status |
ApiConnectionException |
no response (DNS, refused, reset); getPrevious() is the transport's error |
ApiTimeoutException |
an HTTP attempt took longer than the timeout; extends ApiConnectionException |
WaitTimeoutException |
waitForMessage() / waitForCode() / waitForLink() reached their deadline (getPrevious(): the last transient error, if any) |
FakeEmailException |
no API key, a bad option, or a response that is not the API's JSON |
use FakeEmailPro\ErrorCode; use FakeEmailPro\Exception\ApiException; use FakeEmailPro\Exception\QuotaExhaustedException; use FakeEmailPro\Exception\WaitTimeoutException; try { $mailbox = $mail->mailboxes->create(localPart: 'signup-test', domain: 'example.org'); } catch (QuotaExhaustedException $e) { exit("Quota {$e->used}/{$e->limit}, renews {$e->resetsAt?->format(DATE_ATOM)}. More: {$e->upgradeUrl}"); } catch (ApiException $e) { if ($e->errorCode === ErrorCode::PLAN_FORBIDDEN) { // $e->status === 403; $e->getMessage() === "403 plan_forbidden: plan does not allow custom localPart" } throw $e; } try { $code = $mail->waitForCode($address, timeout: 30); } catch (WaitTimeoutException $e) { echo "nothing in {$e->address} within {$e->timeout} s", PHP_EOL; }
Tell errors apart by the class or by $errorCode, never by the message. getCode() is the HTTP status.
Retries and rate limits
The client retries up to maxRetries times (default 2):
429and503, for every method: the server refuses these before doing anything. The wait isRetry-After(at most 60 s). A503whoseRetry-Afteris over 5 s is thrown at once:create()gets one with 60 s when no domain is available, and blocking a test for minutes helps nobody.502,504, Cloudflare's520-524, timeouts and network errors, forGETandDELETEonly, never forPOST(a mailbox could be created twice). Exponential backoff with jitter: 0.5 s, 1 s, 2 s, ... up to 8 s.- A
DELETErepeated after a lost response (timeout, network error,502/504/52x) that gets404counts as done: the lost attempt deleted it. A404on the first attempt is still aNotFoundException.
Inside waitForMessage() and friends the loop retries by itself, up to the deadline whatever maxRetries is:
429, 502, 503, 504, 520-524, network errors and timed-out attempts are waited out, pausing for
Retry-After (cut at the deadline) or 1 s, and each poll asks the server for no more than the time left. When the
deadline passes, you get a WaitTimeoutException, not the HTTP error. Other errors (400, 401, 403, 404,
500) are thrown at once.
Your plan's numbers are in $mail->limits->get(). Every ApiException carries the window state from the
X-RateLimit-* headers as $rateLimit (RateLimitInfo with limit, remaining, reset, or null when the
server did not send them). Each wait request counts once, however long it is held open.
Configuration
use FakeEmailPro\FakeEmail; use FakeEmailPro\Http\CurlTransport; $mail = 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 gets its server timeout + 10 s maxRetries: 2, 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_* ); $mail->withOptions(timeout: 5.0, maxRetries: 0)->domains->list(); // a copy with other settings, for some calls // A wait request keeps its server timeout + 10 s: a shorter withOptions() timeout does not cut the long poll
The constructor throws FakeEmailException when there is no key. Create the client once and share it between
tests: the curl handle is reused, so requests keep the connection alive.
To send requests through your own HTTP stack (a PSR-18 client, a recorder in your tests), implement
FakeEmailPro\Http\Transport: one method that sends a request and returns a FakeEmailPro\Http\Response, or
throws FakeEmailPro\Http\TransportException when there is no response.
Development
composer install composer test # PHPUnit; the live test runs only with FAKE_EMAIL_LIVE=1 and FAKE_EMAIL_API_KEY composer analyse # PHPStan, level max composer cs # PER-CS 2.0 (composer cs-fix to apply)
tests/SpecTest.php checks the models and requests against openapi/public.yaml, a copy of the spec the API
serves; the Spec drift workflow fails when the two differ.
Links
- Product: fake-email.pro/api
- API reference: api.fake-email.pro/docs (OpenAPI: public.yaml)
- SDK docs: fake-email.pro/api/docs/sdks/php
- Packagist: packagist.org/packages/fake-email-pro/fake-email-php
- Issues: github.com/fake-email-pro/fake-email-php/issues
- Changelog: CHANGELOG.md