PHP code example of mailcapture / mailcapture-php

1. Go to this page and download the library: Download mailcapture/mailcapture-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mailcapture / mailcapture-php example snippets


use MailCapture\MailCapture;

$mc = new MailCapture($_ENV['MAILCAPTURE_API_KEY']);
$mc->ping();  // validates key, caches username

// In your test:
$mc->delete('signup');
$yourApp->register($mc->address('signup'));   // e.g. "[email protected]"
$email = $mc->waitFor('signup', timeout: 15.0);

echo $email->subject;   // "Verify your account"
echo $email->otp;       // "123456" — extracted automatically

use MailCapture\MailCapture;
use MailCapture\Model\Capture;
use PHPUnit\Framework\TestCase;

class UserRegistrationTest extends TestCase
{
    private static MailCapture $mc;

    public static function setUpBeforeClass(): void
    {
        self::$mc = new MailCapture($_ENV['MAILCAPTURE_API_KEY']);
        self::$mc->ping();
    }

    protected function setUp(): void
    {
        self::$mc->delete('signup');   // clean inbox before every test
    }

    public function testUserReceivesVerificationEmail(): void
    {
        $inbox = self::$mc->inbox('signup');

        $this->app->register($inbox->getAddress()); // "[email protected]"

        $email = $inbox->waitFor(timeout: 10.0);

        $this->assertSame('Verify your account', $email->subject);
        $this->assertMatchesRegularExpression('/^\d{6}$/', $email->otp);
        $this->assertLessThan(5000, $email->latencyMs);
    }
}

$mc = new MailCapture(
    apiKey: $_ENV['MAILCAPTURE_API_KEY'],
    baseUrl: 'http://localhost:3002',   // override for local dev (default: https://mailcapture.app)
    requestTimeout: 15.0,              // seconds, default 10.0
    username: 'alice',                 // pre-set to skip ping() (optional)
);

$result = $mc->ping();
echo $result->username;          // "alice"
echo $result->addressTemplate;   // "alice-{tag}@mailcapture.app"
echo $result->example;           // "[email protected]"

// Named arguments (recommended)
$email = $mc->waitFor('signup', timeout: 15.0);

// Full options
$email = $mc->waitFor(
    tag: 'signup',
    timeout: 15.0,           // total seconds to wait (default 30)
    pollTimeout: 5,           // per-poll server timeout in seconds, max 30 (default 10)
    after: new DateTime('-30 seconds'),  // only captures after this time
);

$inbox = $mc->inbox('password-reset');

$inbox->getAddress()                    // "[email protected]"
$inbox->waitFor(timeout: 10.0)          // Capture
$inbox->list(limit: 5)                  // CaptureList
$inbox->clear()                         // deletes all captures for this tag

$mc->ping();
echo $mc->address('signup');  // "[email protected]"

$result = $mc->list(tag: 'signup', limit: 10);
foreach ($result->items as $email) {
    echo $email->subject . PHP_EOL;
}

$email->id          // string — UUID
$email->tag         // string — e.g. "signup"
$email->subject     // string — email subject line
$email->otp         // ?string — extracted code, null if none detected
$email->bodyText    // ?string — plain-text body
$email->bodyHtml    // ?string — HTML body
$email->latencyMs   // int — send-to-capture time in ms
$email->status      // string — e.g. "captured"
$email->receivedAt  // string — ISO 8601 timestamp

use MailCapture\Exception\{
    MailCaptureAuthException,
    MailCaptureTimeoutException,
    MailCaptureNotFoundException,
    MailCaptureNetworkException,
};

try {
    $email = $mc->waitFor('signup', timeout: 10.0);
} catch (MailCaptureTimeoutException $e) {
    echo "Waited {$e->getWaitedSeconds()}s for tag: {$e->getTag()}" . PHP_EOL;
    echo "Did the email send? Check your email service logs." . PHP_EOL;
} catch (MailCaptureAuthException $e) {
    echo "Check your MAILCAPTURE_API_KEY environment variable." . PHP_EOL;
} catch (MailCaptureNetworkException $e) {
    echo "Network error: " . $e->getPrevious()?->getMessage() . PHP_EOL;
}

use GuzzleHttp\Client;
use GuzzleHttp\Handler\MockHandler;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Psr7\Response;
use MailCapture\MailCapture;

$mock  = new MockHandler([
    new Response(200, ['Content-Type' => 'application/json'], json_encode([
        'items' => [[
            'id' => 'test-id', 'tag' => 'signup', 'subject' => 'Welcome',
            'otp' => '123456', 'body_text' => null, 'body_html' => null,
            'latency_ms' => 50, 'status' => 'captured',
            'received_at' => '2024-01-01T00:00:00+00:00',
        ]],
        'count' => 1,
        'next_after' => '2024-01-01T00:00:01+00:00',
    ])),
]);
$stack = HandlerStack::create($mock);
$mc    = new MailCapture('mc_testkey', httpClient: new Client(['handler' => $stack]));

$email = $mc->waitFor('signup', timeout: 5.0);
assert($email->otp === '123456');

// Laravel: AppServiceProvider
$this->app->singleton(MailCapture::class, fn() =>
    new MailCapture(config('services.mailcapture.key'))
);

// Symfony: services.yaml
services:
  MailCapture\MailCapture:
    arguments:
      $apiKey: '%env(MAILCAPTURE_API_KEY)%'

$mc = new MailCapture($_ENV['MAILCAPTURE_API_KEY'], baseUrl: 'http://localhost:3002');
bash
composer