Skip to content

PHP and PHPUnit

Terminal window
composer require --dev mailcatchr/mailcatchr
tests/Support/Mail.php
namespace Tests\Support;
use Mailcatchr\Client;
use Mailcatchr\MessageDetail;
trait Mail
{
private static ?Client $mc = null;
protected function mc(): Client
{
return self::$mc ??= new Client(getenv('MAILCATCHR_API_KEY'));
}
/** A fresh address per test so parallel processes never see each other's mail. */
protected function uniqueAddress(string $label): string
{
return sprintf('%s-%d@<mailbox-id>.mailcatchr.com', $label, (int) (microtime(true) * 1000));
}
protected function waitForMail(string $to, ?string $subject = null): MessageDetail
{
$mailboxId = getenv('MAILCATCHR_MAILBOX_ID');
$summary = $this->mc()->messages->waitFor($mailboxId, to: $to, subject: $subject, timeoutSeconds: 30)
?? $this->fail("No email to {$to} within 30 s");
return $this->mc()->messages->get($mailboxId, $summary->id);
}
}
final class PasswordResetTest extends TestCase
{
use Tests\Support\Mail;
public function testResetEmailContainsAWorkingLink(): void
{
$address = $this->uniqueAddress('reset');
$this->post('/password/email', ['email' => $address]);
$message = $this->waitForMail($address, 'Reset your password');
preg_match('#https://\S+/reset\?token=\S+#', (string) $message->textBody, $m);
self::assertNotEmpty($m, 'reset link in the email body');
$this->get($m[0])->assertOk();
}
}

Keep MAIL_MAILER as in production so mail travels through your provider to the mailbox subdomain, or set the testing environment’s mailer to SMTP at smtp.mailcatchr.com:587. Do not use the array or log mailers for these tests: the point is to read what really arrived.

$code = $this->mc()->totps->code(getenv('MAILCATCHR_TOTP_ID'))->code;