From 1e4355f79b5d7850d7c8bbfa98136a9dbd719fa1 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Fri, 13 Nov 2026 04:58:09 +0000 Subject: [PATCH 1/8] feat(laravel): send Mailables and mail notifications through PostHog with the posthog mailer A Laravel app adds `'posthog' => ['transport' => 'posthog']` to config/mail.php and sets MAIL_MAILER=posthog. The mailer registers the core PostHogTransport with templates off and the marker laravel/, only once the app builds a mailer. Each Mailable or mail notification sends under its class name in kebab case as its template key, unless the mail sets X-PostHog-Template-Key; mail without a class uses the mailer's default_template_key. CI installs the Laravel package against the current SDK, as main already does. Ticket: https://github.com/PostHog/michaelr-context/issues/50 Co-Authored-By: Claude Opus 5.5 --- .github/workflows/php.yml | 6 +- packages/laravel/README.md | 38 ++++ packages/laravel/src/Mail/MailDriver.php | 56 +++++ .../laravel/src/PostHogServiceProvider.php | 8 + .../laravel/tests/Fixtures/InvoicePaid.php | 19 ++ .../laravel/tests/Fixtures/OrderShipped.php | 33 +++ .../laravel/tests/Fixtures/SendApiStub.php | 63 ++++++ .../laravel/tests/Fixtures/send-api-stub.php | 54 +++++ packages/laravel/tests/MailDriverTest.php | 205 ++++++++++++++++++ .../tests/MailDriverWithoutMailerTest.php | 52 +++++ 10 files changed, 532 insertions(+), 2 deletions(-) create mode 100644 packages/laravel/src/Mail/MailDriver.php create mode 100644 packages/laravel/tests/Fixtures/InvoicePaid.php create mode 100644 packages/laravel/tests/Fixtures/OrderShipped.php create mode 100644 packages/laravel/tests/Fixtures/SendApiStub.php create mode 100644 packages/laravel/tests/Fixtures/send-api-stub.php create mode 100644 packages/laravel/tests/MailDriverTest.php create mode 100644 packages/laravel/tests/MailDriverWithoutMailerTest.php diff --git a/.github/workflows/php.yml b/.github/workflows/php.yml index d4889dfa..5c8e2ee5 100644 --- a/.github/workflows/php.yml +++ b/.github/workflows/php.yml @@ -72,8 +72,10 @@ jobs: - name: Check public API snapshot run: composer api:check - - name: Install Laravel dependencies - run: composer install --working-dir=packages/laravel --prefer-dist --no-progress + - name: Install Laravel dependencies against the current SDK + run: | + composer --working-dir=packages/laravel config repositories.current-sdk path ../.. + composer install --working-dir=packages/laravel --prefer-dist --no-progress - name: Check Laravel public API snapshot run: composer api:check:laravel diff --git a/packages/laravel/README.md b/packages/laravel/README.md index 2a083a29..9464df4d 100644 --- a/packages/laravel/README.md +++ b/packages/laravel/README.md @@ -266,6 +266,44 @@ No cache is enabled implicitly, and there is no background timer. The PHP client `loadFlags()` remains available for an explicit refresh. You can instead supply a custom provider class in `sdk.flag_definition_cache_provider`. +## Send email + +Add a `posthog` mailer to `config/mail.php` and set `MAIL_MAILER=posthog`. Every +Mailable and mail notification then sends through PostHog's transactional email +API. It needs `POSTHOG_API_KEY` and the project secret key in `POSTHOG_SECRET_KEY`: + +```php +'mailers' => [ + 'posthog' => [ + 'transport' => 'posthog', + // Optional: the template key of mail that has no class, such as Mail::raw(). + 'default_template_key' => 'app-mail', + ], +], +``` + +Each mail sends under its class name in kebab case as its template key, so +`App\Mail\OrderShipped` groups as `order-shipped` in PostHog. Set options on a +Mailable with headers, which never go out with the email: + +```php +public function headers(): Headers +{ + return new Headers(text: [ + 'X-PostHog-Distinct-Id' => (string) $this->order->user_id, + // A queued Mailable retries with the same key, so PostHog sends it once. + 'X-PostHog-Idempotency-Key' => "order-{$this->order->id}-shipped", + ]); +} +``` + +`X-PostHog-Template-Key` overrides the template key. An email PostHog can't carry, +such as one with two `To` addresses or custom headers, throws +`PostHog cannot send this email: ` and sends nothing. A failed send throws +`PostHog\Mailer\PostHogTransportException`, whose `isRetryable()` says whether +sending again with the same idempotency key is safe. Templates made in PostHog +aren't supported here; send them with `PostHog::client()->emails()->send()`. + ## Configuration callbacks and full PHP access `posthog.sdk` passes PHP SDK options through. `before_send`, `error_handler`, and diff --git a/packages/laravel/src/Mail/MailDriver.php b/packages/laravel/src/Mail/MailDriver.php new file mode 100644 index 00000000..33114902 --- /dev/null +++ b/packages/laravel/src/Mail/MailDriver.php @@ -0,0 +1,56 @@ + 'posthog'` through PostHog's transactional email API. + * + * Each mail sends under its Mailable or notification class in kebab case as its template key, so + * `App\Mail\OrderShipped` sends as `order-shipped`. An `X-PostHog-Template-Key` header on the mail wins; + * mail with no class, such as `Mail::raw()`, uses the mailer's `default_template_key`, or `laravel`. + */ +final class MailDriver +{ + private const TRANSPORT = 'posthog'; + private const INTEGRATION = 'laravel'; + private const TEMPLATE_KEY = 'X-PostHog-Template-Key'; + + public static function extend(MailManager $manager): void + { + $manager->extend(self::TRANSPORT, static fn(array $config): PostHogTransport => new PostHogTransport( + // Resolved per mailer, so each Octane request's mailer sends with that request's client. + Container::getInstance()->make(PostHog::class)->client()->emails(), + integration: self::INTEGRATION . '/' . PostHog::VERSION, + defaultTemplateKey: $config['default_template_key'] ?? null, + templates: false, + )); + } + + public static function nameTheMail(MessageSending $event, Repository $config): void + { + $mailer = $event->data['mailer'] ?? null; + $mailers = $config->get('mail.mailers', []); + if (!is_string($mailer) || ($mailers[$mailer]['transport'] ?? null) !== self::TRANSPORT) { + return; + } + $class = $event->data['__laravel_mailable'] ?? $event->data['__laravel_notification'] ?? null; + $headers = $event->message->getHeaders(); + if (!is_string($class) || $headers->has(self::TEMPLATE_KEY)) { + return; + } + $key = preg_replace('/[^a-zA-Z0-9_-]+/', '-', Str::kebab(class_basename($class))); + $key = substr(trim((string) $key, '-'), 0, 400); + if ($key !== '') { + $headers->addTextHeader(self::TEMPLATE_KEY, $key); + } + } +} diff --git a/packages/laravel/src/PostHogServiceProvider.php b/packages/laravel/src/PostHogServiceProvider.php index 397bcfb4..8c8eb863 100644 --- a/packages/laravel/src/PostHogServiceProvider.php +++ b/packages/laravel/src/PostHogServiceProvider.php @@ -10,6 +10,9 @@ use Illuminate\Queue\Events\JobProcessed; use Illuminate\Queue\Events\JobExceptionOccurred; use Illuminate\Queue\Events\Looping; +use Illuminate\Mail\Events\MessageSending; +use Illuminate\Mail\MailManager; +use PostHog\Laravel\Mail\MailDriver; use PostHog\Laravel\Middleware\RequestContext as RequestContextMiddleware; use Illuminate\Support\ServiceProvider; use Throwable; @@ -87,6 +90,11 @@ public function boot(): void 'laravel.queue_job', ); }); + // Only an app that builds a mailer loads Laravel's mailer, Symfony Mailer and the PostHog transport. + $this->callAfterResolving('mail.manager', fn (MailManager $manager) => MailDriver::extend($manager)); + $events->listen(MessageSending::class, function (MessageSending $event) { + MailDriver::nameTheMail($event, Container::getInstance()['config']); + }); $events->listen(CommandStarting::class, function () { // The first CLI kernel may already be handling input when package providers boot. Container::getInstance()->make(ConsoleLifecycle::class)->startRoot(); diff --git a/packages/laravel/tests/Fixtures/InvoicePaid.php b/packages/laravel/tests/Fixtures/InvoicePaid.php new file mode 100644 index 00000000..f93596a7 --- /dev/null +++ b/packages/laravel/tests/Fixtures/InvoicePaid.php @@ -0,0 +1,19 @@ +from('billing@example.com')->subject('Invoice paid')->line('Thanks!'); + } +} diff --git a/packages/laravel/tests/Fixtures/OrderShipped.php b/packages/laravel/tests/Fixtures/OrderShipped.php new file mode 100644 index 00000000..0608864d --- /dev/null +++ b/packages/laravel/tests/Fixtures/OrderShipped.php @@ -0,0 +1,33 @@ + $headers + */ + public function __construct(private readonly array $headers = []) + { + } + + public function envelope(): Envelope + { + return new Envelope(from: 'shop@example.com', subject: 'Your order shipped'); + } + + public function content(): Content + { + return new Content(htmlString: '

On its way.

'); + } + + public function headers(): Headers + { + return new Headers(text: $this->headers); + } +} diff --git a/packages/laravel/tests/Fixtures/SendApiStub.php b/packages/laravel/tests/Fixtures/SendApiStub.php new file mode 100644 index 00000000..5839bb04 --- /dev/null +++ b/packages/laravel/tests/Fixtures/SendApiStub.php @@ -0,0 +1,63 @@ +}> $responses + */ + public function __construct(array $responses) + { + $this->requestsFile = tempnam(sys_get_temp_dir(), 'posthog-send-'); + $process = proc_open( + [PHP_BINARY, __DIR__ . '/send-api-stub.php', $this->requestsFile, json_encode($responses)], + [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], + $pipes + ); + if (!is_resource($process)) { + throw new RuntimeException('Could not start the send API stub.'); + } + $this->process = $process; + $address = fgets($pipes[1]); + if ($address === false) { + throw new RuntimeException('The send API stub did not start: ' . stream_get_contents($pipes[2])); + } + $this->address = trim($address); + } + + public function url(): string + { + return 'http://' . $this->address; + } + + /** + * @return list, body: string}> + */ + public function requests(): array + { + $lines = array_filter(explode("\n", (string) file_get_contents($this->requestsFile))); + + return array_values(array_map( + static fn(string $line): array => json_decode($line, true, 512, JSON_THROW_ON_ERROR), + $lines + )); + } + + public function stop(): void + { + proc_terminate($this->process); + proc_close($this->process); + @unlink($this->requestsFile); + } +} diff --git a/packages/laravel/tests/Fixtures/send-api-stub.php b/packages/laravel/tests/Fixtures/send-api-stub.php new file mode 100644 index 00000000..91b3b54b --- /dev/null +++ b/packages/laravel/tests/Fixtures/send-api-stub.php @@ -0,0 +1,54 @@ + + +$server = stream_socket_server('tcp://127.0.0.1:0', $errno, $error); +if ($server === false) { + fwrite(STDERR, $error); + exit(1); +} +$responses = json_decode($argv[2], true, 512, JSON_THROW_ON_ERROR); +echo stream_socket_get_name($server, false) . "\n"; +flush(); + +while ($connection = @stream_socket_accept($server, 30)) { + stream_set_timeout($connection, 5); + $requestLine = trim((string) fgets($connection)); + $headers = []; + while (($line = fgets($connection)) !== false && trim($line) !== '') { + [$name, $value] = explode(':', $line, 2); + $headers[strtolower($name)] = trim($value); + } + if (strtolower($headers['expect'] ?? '') === '100-continue') { + fwrite($connection, "HTTP/1.1 100 Continue\r\n\r\n"); + } + $length = (int) ($headers['content-length'] ?? 0); + $body = ''; + while (strlen($body) < $length) { + $chunk = fread($connection, $length - strlen($body)); + if ($chunk === false || $chunk === '') { + break; + } + $body .= $chunk; + } + if (($headers['content-encoding'] ?? '') === 'gzip') { + $body = gzdecode($body); + } + file_put_contents($argv[1], json_encode( + ['requestLine' => $requestLine, 'headers' => $headers, 'body' => $body], + JSON_THROW_ON_ERROR + ) . "\n", FILE_APPEND); + + $response = array_shift($responses) ?? ['status' => 500, 'body' => '{"type":"server_error"}']; + $status = $response['status']; + $payload = $response['body'] ?? ''; + $extra = ''; + foreach ($response['headers'] ?? [] as $name => $value) { + $extra .= "$name: $value\r\n"; + } + fwrite($connection, "HTTP/1.1 $status Response\r\nContent-Type: application/json\r\n$extra" + . 'Content-Length: ' . strlen($payload) . "\r\nConnection: close\r\n\r\n" . $payload); + fclose($connection); +} diff --git a/packages/laravel/tests/MailDriverTest.php b/packages/laravel/tests/MailDriverTest.php new file mode 100644 index 00000000..d4874818 --- /dev/null +++ b/packages/laravel/tests/MailDriverTest.php @@ -0,0 +1,205 @@ + 202, 'body' => '{"message_id":"' . self::MESSAGE_ID . '","replayed":false}']; + + private ?SendApiStub $api = null; + + protected function getPackageProviders($app): array + { + return [PostHogServiceProvider::class]; + } + + protected function defineEnvironment($app): void + { + $app['config']->set('posthog.api_key', 'phc_project'); + $app['config']->set('posthog.secret_key', 'phs_secret'); + $app['config']->set('posthog.sdk.consumer', 'noop'); + $app['config']->set('mail.default', 'posthog'); + $app['config']->set('mail.mailers.posthog', ['transport' => 'posthog']); + } + + protected function tearDown(): void + { + $this->api?->stop(); + parent::tearDown(); + } + + /** + * @param list}> $responses + */ + private function sendApi(array $responses = [self::SENT]): SendApiStub + { + $this->api = new SendApiStub($responses); + $this->app['config']->set('posthog.sdk.app_host', $this->api->url()); + + return $this->api; + } + + /** + * @return array + */ + private function onlySend(): array + { + $requests = $this->api->requests(); + $this->assertCount(1, $requests); + $this->assertSame('POST /api/projects/@current/messaging/send/email/ HTTP/1.1', $requests[0]['requestLine']); + $this->assertSame('Bearer phs_secret', $requests[0]['headers']['authorization']); + + return $requests[0]; + } + + public function testAMailableSendsThroughThePostHogMailerUnderItsClassName(): void + { + $this->sendApi(); + + $sent = Mail::to('ana@example.com')->send(new OrderShipped()); + + $request = $this->onlySend(); + $this->assertSame('laravel/' . PostHog::VERSION, $request['headers']['x-posthog-integration']); + $this->assertSame([ + 'template_key' => 'order-shipped', + 'subject' => 'Your order shipped', + 'html' => '

On its way.

', + 'from' => 'shop@example.com', + 'to' => 'ana@example.com', + ], array_diff_key(json_decode($request['body'], true), ['capture_engagement' => true])); + $this->assertSame(self::MESSAGE_ID, $sent->getMessageId()); + } + + public function testAMailNotificationSendsUnderTheNotificationClassName(): void + { + $this->sendApi(); + + Notification::send( + (new AnonymousNotifiable())->route('mail', 'ana@example.com'), + new InvoicePaid() + ); + + $body = json_decode($this->onlySend()['body'], true); + $this->assertSame('invoice-paid', $body['template_key']); + $this->assertSame('Invoice paid', $body['subject']); + $this->assertSame('ana@example.com', $body['to']); + } + + public function testTheMailableSetsItsOwnTemplateKeyAndOptionsInHeaders(): void + { + $this->sendApi(); + + Mail::to('ana@example.com')->send(new OrderShipped([ + 'X-PostHog-Template-Key' => 'shipping-v2', + 'X-PostHog-Distinct-Id' => 'user_123', + 'X-PostHog-Idempotency-Key' => 'order-42:order-shipped', + ])); + + $request = $this->onlySend(); + $body = json_decode($request['body'], true); + $this->assertSame('shipping-v2', $body['template_key']); + $this->assertSame('user_123', $body['distinct_id']); + $this->assertSame('order-42:order-shipped', $request['headers']['idempotency-key']); + } + + public function testMailWithNoClassSendsUnderTheMailersDefaultTemplateKey(): void + { + $this->app['config']->set('mail.mailers.posthog.default_template_key', 'receipts'); + $this->sendApi(); + + Mail::raw('Thanks for your order.', function ($message) { + $message->from('shop@example.com')->to('ana@example.com')->subject('Receipt'); + }); + + $this->assertSame('receipts', json_decode($this->onlySend()['body'], true)['template_key']); + } + + public function testMailWithNoClassAndNoDefaultSendsUnderTheIntegrationName(): void + { + $this->sendApi(); + + Mail::raw('Thanks for your order.', function ($message) { + $message->from('shop@example.com')->to('ana@example.com')->subject('Receipt'); + }); + + $this->assertSame('laravel', json_decode($this->onlySend()['body'], true)['template_key']); + } + + public function testAnotherMailerSendsTheMailableWithoutPostHogHeaders(): void + { + $this->app['config']->set('mail.mailers.archive', ['transport' => 'array']); + + Mail::mailer('archive')->to('ana@example.com')->send(new OrderShipped()); + + $messages = Mail::mailer('archive')->getSymfonyTransport()->messages(); + $this->assertCount(1, $messages); + $this->assertFalse($messages[0]->getOriginalMessage()->getHeaders()->has('X-PostHog-Template-Key')); + } + + public function testAMailablePostHogCannotCarryIsRefusedWithoutASend(): void + { + $this->sendApi(); + + try { + Mail::to(['ana@example.com', 'ben@example.com'])->send(new OrderShipped()); + $this->fail('A mail to two recipients was sent.'); + } catch (LogicException $refusal) { + $this->assertStringStartsWith('PostHog cannot send this email: multiple_to', $refusal->getMessage()); + } + $this->assertSame([], $this->api->requests()); + } + + public function testAFailedSendThrowsTheTransportErrorWithItsRetryAdvice(): void + { + $this->sendApi([[ + 'status' => 400, + 'body' => '{"type":"validation_error","code":"invalid_input","detail":"Bad from.","attr":"from"}', + ]]); + + try { + Mail::to('ana@example.com')->send(new OrderShipped()); + $this->fail('A rejected send did not throw.'); + } catch (PostHogTransportException $error) { + $this->assertSame(400, $error->getStatusCode()); + $this->assertSame('from', $error->getField()); + $this->assertFalse($error->isRetryable()); + } + } + + public function testATemplateMadeInPostHogIsRefused(): void + { + if (!class_exists(RemoteTemplateEmail::class)) { + $this->markTestSkipped('Symfony Mailer before 8.2 has no RemoteTemplateEmail to send a template.'); + } + $this->sendApi(); + $email = (new RemoteTemplateEmail()) + ->from('shop@example.com') + ->to('ana@example.com') + ->template('0190f6d2-7c1e-7b3a-9f5e-1c2d3e4f5a6b'); + + try { + Mail::mailer('posthog')->getSymfonyTransport()->send($email); + $this->fail('A template was sent.'); + } catch (LogicException $refusal) { + $this->assertStringStartsWith( + 'PostHog cannot send this email: template_unsupported', + $refusal->getMessage() + ); + } + $this->assertSame([], $this->api->requests()); + } +} diff --git a/packages/laravel/tests/MailDriverWithoutMailerTest.php b/packages/laravel/tests/MailDriverWithoutMailerTest.php new file mode 100644 index 00000000..97a6c578 --- /dev/null +++ b/packages/laravel/tests/MailDriverWithoutMailerTest.php @@ -0,0 +1,52 @@ +set('posthog.api_key', 'phc_project'); + $app['config']->set('posthog.sdk.consumer', 'noop'); + } + + public function testThePackageBootsAndCapturesWithoutLoadingAMailer(): void + { + $fake = PostHog::fake(); + + PostHog::capture('order completed', [], 'user_123'); + + $fake->assertCaptured('order completed'); + } +} From c61f0d6f2931fd1fad59078ef013af70a84277c7 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Fri, 13 Nov 2026 06:02:33 +0000 Subject: [PATCH 2/8] fix(laravel): name mail sent through failover and on-demand mailers, and send with each job's client The posthog transport now remembers each mail's class name when Laravel sends it and reads it at the transport, so Mailables keep their class-name template key inside failover, round-robin and on-demand mailers, while every other transport sends the mail untouched. It builds the core transport per send, so each queued job, request or Octane worker sends with its own scoped client and configuration. Derived keys are cut to the send API's 256 characters. The tests use the core SDK's loopback server, and check that an app that sends no mail builds no mailer, in place of an autoload spy. Ticket: https://github.com/PostHog/michaelr-context/issues/50 Co-Authored-By: Claude Opus 5.5 --- packages/laravel/src/Mail/MailDriver.php | 96 ++++++++++--- .../laravel/src/PostHogServiceProvider.php | 4 +- .../laravel/tests/Fixtures/SendApiStub.php | 63 -------- .../laravel/tests/Fixtures/send-api-stub.php | 54 ------- packages/laravel/tests/MailDriverTest.php | 136 ++++++++++++++---- .../tests/MailDriverWithoutMailerTest.php | 52 ------- 6 files changed, 186 insertions(+), 219 deletions(-) delete mode 100644 packages/laravel/tests/Fixtures/SendApiStub.php delete mode 100644 packages/laravel/tests/Fixtures/send-api-stub.php delete mode 100644 packages/laravel/tests/MailDriverWithoutMailerTest.php diff --git a/packages/laravel/src/Mail/MailDriver.php b/packages/laravel/src/Mail/MailDriver.php index 33114902..0df5022b 100644 --- a/packages/laravel/src/Mail/MailDriver.php +++ b/packages/laravel/src/Mail/MailDriver.php @@ -3,54 +3,106 @@ namespace PostHog\Laravel\Mail; use Illuminate\Container\Container; -use Illuminate\Contracts\Config\Repository; use Illuminate\Mail\Events\MessageSending; use Illuminate\Mail\MailManager; use Illuminate\Support\Str; use PostHog\Laravel\PostHog; use PostHog\Mailer\PostHogTransport; +use Symfony\Component\Mailer\Envelope; +use Symfony\Component\Mailer\SentMessage; +use Symfony\Component\Mailer\Transport\TransportInterface; +use Symfony\Component\Mime\Message; +use Symfony\Component\Mime\RawMessage; +use WeakMap; /** - * @internal Registers the `posthog` mail transport, which sends every Mailable and mail notification of a - * mailer with `'transport' => 'posthog'` through PostHog's transactional email API. + * @internal The `posthog` mail transport, which sends every Mailable and mail notification of a mailer with + * `'transport' => 'posthog'` through PostHog's transactional email API, also inside a failover, round-robin + * or on-demand mailer. * * Each mail sends under its Mailable or notification class in kebab case as its template key, so * `App\Mail\OrderShipped` sends as `order-shipped`. An `X-PostHog-Template-Key` header on the mail wins; * mail with no class, such as `Mail::raw()`, uses the mailer's `default_template_key`, or `laravel`. */ -final class MailDriver +final class MailDriver implements TransportInterface { - private const TRANSPORT = 'posthog'; private const INTEGRATION = 'laravel'; private const TEMPLATE_KEY = 'X-PostHog-Template-Key'; + // The longest template key the send API takes. + private const TEMPLATE_KEY_LENGTH = 256; + + /** @var WeakMap|null The template key of each mail Laravel is sending. */ + private static ?WeakMap $templateKeys = null; + + private function __construct(private readonly ?string $defaultTemplateKey) + { + } public static function extend(MailManager $manager): void { - $manager->extend(self::TRANSPORT, static fn(array $config): PostHogTransport => new PostHogTransport( - // Resolved per mailer, so each Octane request's mailer sends with that request's client. - Container::getInstance()->make(PostHog::class)->client()->emails(), - integration: self::INTEGRATION . '/' . PostHog::VERSION, - defaultTemplateKey: $config['default_template_key'] ?? null, - templates: false, - )); + $manager->extend( + 'posthog', + static fn(array $config): self => new self($config['default_template_key'] ?? null) + ); } - public static function nameTheMail(MessageSending $event, Repository $config): void + /** + * Remembers the mail's class as its template key for the PostHog transport. The mail itself is left as is, + * so no other transport, such as the next one of a failover mailer, sends a PostHog header. + */ + public static function nameTheMail(MessageSending $event): void { - $mailer = $event->data['mailer'] ?? null; - $mailers = $config->get('mail.mailers', []); - if (!is_string($mailer) || ($mailers[$mailer]['transport'] ?? null) !== self::TRANSPORT) { - return; - } $class = $event->data['__laravel_mailable'] ?? $event->data['__laravel_notification'] ?? null; - $headers = $event->message->getHeaders(); - if (!is_string($class) || $headers->has(self::TEMPLATE_KEY)) { + if (!is_string($class)) { return; } $key = preg_replace('/[^a-zA-Z0-9_-]+/', '-', Str::kebab(class_basename($class))); - $key = substr(trim((string) $key, '-'), 0, 400); + $key = substr(trim((string) $key, '-'), 0, self::TEMPLATE_KEY_LENGTH); if ($key !== '') { - $headers->addTextHeader(self::TEMPLATE_KEY, $key); + self::$templateKeys ??= new WeakMap(); + self::$templateKeys[$event->message] = $key; + } + } + + public function send(RawMessage $message, ?Envelope $envelope = null): ?SentMessage + { + $key = self::templateKeyOf($message); + if ($key !== null && $message instanceof Message && !$message->getHeaders()->has(self::TEMPLATE_KEY)) { + // PostHogTransport reads the reserved header and strips it, so it never goes out. + $message->getHeaders()->addTextHeader(self::TEMPLATE_KEY, $key); + } + + // Built per send, so each request, job or Octane worker sends with its own scoped client. + $transport = new PostHogTransport( + Container::getInstance()->make(PostHog::class)->client()->emails(), + integration: self::INTEGRATION . '/' . PostHog::VERSION, + defaultTemplateKey: $this->defaultTemplateKey, + templates: false, + ); + + return $transport->send($message, $envelope); + } + + private static function templateKeyOf(RawMessage $message): ?string + { + if (self::$templateKeys === null) { + return null; + } + if (isset(self::$templateKeys[$message])) { + return self::$templateKeys[$message]; } + // A failover or round-robin mailer sends each transport a clone of the mail, equal to it until sent. + foreach (self::$templateKeys as $mail => $key) { + if ($mail == $message) { + return $key; + } + } + + return null; + } + + public function __toString(): string + { + return 'posthog'; } } diff --git a/packages/laravel/src/PostHogServiceProvider.php b/packages/laravel/src/PostHogServiceProvider.php index 4c1816b5..0aea6efc 100644 --- a/packages/laravel/src/PostHogServiceProvider.php +++ b/packages/laravel/src/PostHogServiceProvider.php @@ -97,9 +97,7 @@ public function boot(): void }); // Only an app that builds a mailer loads Laravel's mailer, Symfony Mailer and the PostHog transport. $this->callAfterResolving('mail.manager', fn (MailManager $manager) => MailDriver::extend($manager)); - $events->listen(MessageSending::class, function (MessageSending $event) { - MailDriver::nameTheMail($event, Container::getInstance()['config']); - }); + $events->listen(MessageSending::class, fn (MessageSending $event) => MailDriver::nameTheMail($event)); $events->listen(CommandStarting::class, function () { // The first CLI kernel may already be handling input when package providers boot. Container::getInstance()->make(ConsoleLifecycle::class)->startRoot(); diff --git a/packages/laravel/tests/Fixtures/SendApiStub.php b/packages/laravel/tests/Fixtures/SendApiStub.php deleted file mode 100644 index 5839bb04..00000000 --- a/packages/laravel/tests/Fixtures/SendApiStub.php +++ /dev/null @@ -1,63 +0,0 @@ -}> $responses - */ - public function __construct(array $responses) - { - $this->requestsFile = tempnam(sys_get_temp_dir(), 'posthog-send-'); - $process = proc_open( - [PHP_BINARY, __DIR__ . '/send-api-stub.php', $this->requestsFile, json_encode($responses)], - [1 => ['pipe', 'w'], 2 => ['pipe', 'w']], - $pipes - ); - if (!is_resource($process)) { - throw new RuntimeException('Could not start the send API stub.'); - } - $this->process = $process; - $address = fgets($pipes[1]); - if ($address === false) { - throw new RuntimeException('The send API stub did not start: ' . stream_get_contents($pipes[2])); - } - $this->address = trim($address); - } - - public function url(): string - { - return 'http://' . $this->address; - } - - /** - * @return list, body: string}> - */ - public function requests(): array - { - $lines = array_filter(explode("\n", (string) file_get_contents($this->requestsFile))); - - return array_values(array_map( - static fn(string $line): array => json_decode($line, true, 512, JSON_THROW_ON_ERROR), - $lines - )); - } - - public function stop(): void - { - proc_terminate($this->process); - proc_close($this->process); - @unlink($this->requestsFile); - } -} diff --git a/packages/laravel/tests/Fixtures/send-api-stub.php b/packages/laravel/tests/Fixtures/send-api-stub.php deleted file mode 100644 index 91b3b54b..00000000 --- a/packages/laravel/tests/Fixtures/send-api-stub.php +++ /dev/null @@ -1,54 +0,0 @@ - - -$server = stream_socket_server('tcp://127.0.0.1:0', $errno, $error); -if ($server === false) { - fwrite(STDERR, $error); - exit(1); -} -$responses = json_decode($argv[2], true, 512, JSON_THROW_ON_ERROR); -echo stream_socket_get_name($server, false) . "\n"; -flush(); - -while ($connection = @stream_socket_accept($server, 30)) { - stream_set_timeout($connection, 5); - $requestLine = trim((string) fgets($connection)); - $headers = []; - while (($line = fgets($connection)) !== false && trim($line) !== '') { - [$name, $value] = explode(':', $line, 2); - $headers[strtolower($name)] = trim($value); - } - if (strtolower($headers['expect'] ?? '') === '100-continue') { - fwrite($connection, "HTTP/1.1 100 Continue\r\n\r\n"); - } - $length = (int) ($headers['content-length'] ?? 0); - $body = ''; - while (strlen($body) < $length) { - $chunk = fread($connection, $length - strlen($body)); - if ($chunk === false || $chunk === '') { - break; - } - $body .= $chunk; - } - if (($headers['content-encoding'] ?? '') === 'gzip') { - $body = gzdecode($body); - } - file_put_contents($argv[1], json_encode( - ['requestLine' => $requestLine, 'headers' => $headers, 'body' => $body], - JSON_THROW_ON_ERROR - ) . "\n", FILE_APPEND); - - $response = array_shift($responses) ?? ['status' => 500, 'body' => '{"type":"server_error"}']; - $status = $response['status']; - $payload = $response['body'] ?? ''; - $extra = ''; - foreach ($response['headers'] ?? [] as $name => $value) { - $extra .= "$name: $value\r\n"; - } - fwrite($connection, "HTTP/1.1 $status Response\r\nContent-Type: application/json\r\n$extra" - . 'Content-Length: ' . strlen($payload) . "\r\nConnection: close\r\n\r\n" . $payload); - fclose($connection); -} diff --git a/packages/laravel/tests/MailDriverTest.php b/packages/laravel/tests/MailDriverTest.php index d4874818..009dc527 100644 --- a/packages/laravel/tests/MailDriverTest.php +++ b/packages/laravel/tests/MailDriverTest.php @@ -2,16 +2,19 @@ namespace PostHog\Laravel\Tests; +use Illuminate\Mail\Events\MessageSent; use Illuminate\Notifications\AnonymousNotifiable; +use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Notification; use Orchestra\Testbench\TestCase; +use PostHog\Laravel\Facades\PostHog as PostHogFacade; use PostHog\Laravel\PostHog; use PostHog\Laravel\PostHogServiceProvider; use PostHog\Laravel\Tests\Fixtures\InvoicePaid; use PostHog\Laravel\Tests\Fixtures\OrderShipped; -use PostHog\Laravel\Tests\Fixtures\SendApiStub; use PostHog\Mailer\PostHogTransportException; +use PostHog\Test\LocalHttpServer; use Symfony\Component\Mailer\Exception\LogicException; use Symfony\Component\Mailer\RemoteTemplateEmail; @@ -19,8 +22,9 @@ class MailDriverTest extends TestCase { private const MESSAGE_ID = '01a18356-c56c-0001-e494-7666bc915188'; private const SENT = ['status' => 202, 'body' => '{"message_id":"' . self::MESSAGE_ID . '","replayed":false}']; + private const FAILOVER = ['transport' => 'failover', 'mailers' => ['posthog', 'archive']]; - private ?SendApiStub $api = null; + private ?LocalHttpServer $api = null; protected function getPackageProviders($app): array { @@ -34,6 +38,7 @@ protected function defineEnvironment($app): void $app['config']->set('posthog.sdk.consumer', 'noop'); $app['config']->set('mail.default', 'posthog'); $app['config']->set('mail.mailers.posthog', ['transport' => 'posthog']); + $app['config']->set('mail.mailers.archive', ['transport' => 'array']); } protected function tearDown(): void @@ -42,30 +47,33 @@ protected function tearDown(): void parent::tearDown(); } - /** - * @param list}> $responses - */ - private function sendApi(array $responses = [self::SENT]): SendApiStub + private function sendApi(array $responses = [self::SENT]): LocalHttpServer { - $this->api = new SendApiStub($responses); - $this->app['config']->set('posthog.sdk.app_host', $this->api->url()); + // The core SDK's loopback HTTP server, which records each request it answers. + require_once __DIR__ . '/../../../test/LocalHttpServer.php'; + $this->api = new LocalHttpServer($responses); + $this->app['config']->set('posthog.sdk.app_host', 'http://' . $this->api->address()); return $this->api; } /** - * @return array + * @return array{requestLine: string, headers: array, body: string} */ private function onlySend(): array { $requests = $this->api->requests(); $this->assertCount(1, $requests); $this->assertSame('POST /api/projects/@current/messaging/send/email/ HTTP/1.1', $requests[0]['requestLine']); - $this->assertSame('Bearer phs_secret', $requests[0]['headers']['authorization']); return $requests[0]; } + private function templateKeyOfOnlySend(): string + { + return json_decode($this->onlySend()['body'], true)['template_key']; + } + public function testAMailableSendsThroughThePostHogMailerUnderItsClassName(): void { $this->sendApi(); @@ -73,14 +81,14 @@ public function testAMailableSendsThroughThePostHogMailerUnderItsClassName(): vo $sent = Mail::to('ana@example.com')->send(new OrderShipped()); $request = $this->onlySend(); + $this->assertSame('Bearer phs_secret', $request['headers']['authorization']); $this->assertSame('laravel/' . PostHog::VERSION, $request['headers']['x-posthog-integration']); - $this->assertSame([ - 'template_key' => 'order-shipped', - 'subject' => 'Your order shipped', - 'html' => '

On its way.

', - 'from' => 'shop@example.com', - 'to' => 'ana@example.com', - ], array_diff_key(json_decode($request['body'], true), ['capture_engagement' => true])); + $body = json_decode($request['body'], true); + $this->assertSame('order-shipped', $body['template_key']); + $this->assertSame('ana@example.com', $body['to']); + $this->assertSame('shop@example.com', $body['from']); + $this->assertSame('Your order shipped', $body['subject']); + $this->assertSame('

On its way.

', $body['html']); $this->assertSame(self::MESSAGE_ID, $sent->getMessageId()); } @@ -99,6 +107,69 @@ public function testAMailNotificationSendsUnderTheNotificationClassName(): void $this->assertSame('ana@example.com', $body['to']); } + public function testAMailableSendsUnderItsClassNameThroughAFailoverMailer(): void + { + $this->app['config']->set('mail.mailers.failover', self::FAILOVER); + $this->sendApi(); + + Mail::mailer('failover')->to('ana@example.com')->send(new OrderShipped()); + + $this->assertSame('order-shipped', $this->templateKeyOfOnlySend()); + } + + public function testAMailableSendsUnderItsClassNameThroughAMailerBuiltOnDemand(): void + { + $this->sendApi(); + + Mail::build(['transport' => 'posthog'])->to('ana@example.com')->send(new OrderShipped()); + + $this->assertSame('order-shipped', $this->templateKeyOfOnlySend()); + } + + public function testAMailableFailingOverFromPostHogReachesTheNextMailerWithoutPostHogHeaders(): void + { + $this->app['config']->set('mail.mailers.failover', self::FAILOVER); + $this->sendApi([[ + 'status' => 400, + 'body' => '{"type":"validation_error","code":"invalid_input","detail":"Bad."}', + ]]); + + $sent = []; + Event::listen(MessageSent::class, function (MessageSent $event) use (&$sent) { + $sent[] = $event->message; + }); + + Mail::mailer('failover')->to('ana@example.com')->send(new OrderShipped()); + + $this->assertCount(1, $this->api->requests()); + $this->assertCount(1, $sent); + $this->assertFalse($sent[0]->getHeaders()->has('X-PostHog-Template-Key')); + } + + public function testAnotherMailerSendsTheMailableWithoutPostHogHeaders(): void + { + Mail::mailer('archive')->to('ana@example.com')->send(new OrderShipped()); + + $messages = Mail::mailer('archive')->getSymfonyTransport()->messages(); + $this->assertCount(1, $messages); + $this->assertFalse($messages[0]->getOriginalMessage()->getHeaders()->has('X-PostHog-Template-Key')); + } + + public function testAClassNameLongerThanTheTemplateKeyLimitIsCutToFit(): void + { + // A class name this long would outgrow a file name, so the test declares it. + $name = 'OrderShipped' . str_repeat('AndEverythingElse', 20); + eval("namespace PostHog\\Laravel\\Tests\\Fixtures; class $name extends OrderShipped {}"); + $mailable = 'PostHog\\Laravel\\Tests\\Fixtures\\' . $name; + $this->sendApi(); + + Mail::to('ana@example.com')->send(new $mailable()); + + $key = $this->templateKeyOfOnlySend(); + $this->assertSame(256, strlen($key)); + $this->assertStringStartsWith('order-shipped-and-everything-else-and-everything-else', $key); + } + public function testTheMailableSetsItsOwnTemplateKeyAndOptionsInHeaders(): void { $this->sendApi(); @@ -125,7 +196,7 @@ public function testMailWithNoClassSendsUnderTheMailersDefaultTemplateKey(): voi $message->from('shop@example.com')->to('ana@example.com')->subject('Receipt'); }); - $this->assertSame('receipts', json_decode($this->onlySend()['body'], true)['template_key']); + $this->assertSame('receipts', $this->templateKeyOfOnlySend()); } public function testMailWithNoClassAndNoDefaultSendsUnderTheIntegrationName(): void @@ -136,18 +207,23 @@ public function testMailWithNoClassAndNoDefaultSendsUnderTheIntegrationName(): v $message->from('shop@example.com')->to('ana@example.com')->subject('Receipt'); }); - $this->assertSame('laravel', json_decode($this->onlySend()['body'], true)['template_key']); + $this->assertSame('laravel', $this->templateKeyOfOnlySend()); } - public function testAnotherMailerSendsTheMailableWithoutPostHogHeaders(): void + public function testEachQueuedJobSendsWithItsOwnPostHogConfiguration(): void { - $this->app['config']->set('mail.mailers.archive', ['transport' => 'array']); + $this->sendApi([self::SENT, self::SENT]); + Mail::to('ana@example.com')->send(new OrderShipped()); - Mail::mailer('archive')->to('ana@example.com')->send(new OrderShipped()); + // A queue worker starts each job with fresh scoped services, such as a tenant's own secret key. + $this->app['config']->set('posthog.secret_key', 'phs_tenant'); + $this->app->forgetScopedInstances(); + Mail::to('ben@example.com')->send(new OrderShipped()); - $messages = Mail::mailer('archive')->getSymfonyTransport()->messages(); - $this->assertCount(1, $messages); - $this->assertFalse($messages[0]->getOriginalMessage()->getHeaders()->has('X-PostHog-Template-Key')); + $requests = $this->api->requests(); + $this->assertCount(2, $requests); + $this->assertSame('Bearer phs_secret', $requests[0]['headers']['authorization']); + $this->assertSame('Bearer phs_tenant', $requests[1]['headers']['authorization']); } public function testAMailablePostHogCannotCarryIsRefusedWithoutASend(): void @@ -202,4 +278,14 @@ public function testATemplateMadeInPostHogIsRefused(): void } $this->assertSame([], $this->api->requests()); } + + public function testAnAppThatSendsNoMailBuildsNoMailer(): void + { + $fake = PostHogFacade::fake(); + + PostHogFacade::capture('order completed', [], 'user_123'); + + $fake->assertCaptured('order completed'); + $this->assertFalse($this->app->resolved('mail.manager')); + } } diff --git a/packages/laravel/tests/MailDriverWithoutMailerTest.php b/packages/laravel/tests/MailDriverWithoutMailerTest.php deleted file mode 100644 index 97a6c578..00000000 --- a/packages/laravel/tests/MailDriverWithoutMailerTest.php +++ /dev/null @@ -1,52 +0,0 @@ -set('posthog.api_key', 'phc_project'); - $app['config']->set('posthog.sdk.consumer', 'noop'); - } - - public function testThePackageBootsAndCapturesWithoutLoadingAMailer(): void - { - $fake = PostHog::fake(); - - PostHog::capture('order completed', [], 'user_123'); - - $fake->assertCaptured('order completed'); - } -} From 6eba8520268cb41309b05c4f1d8335f5f217c860 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Fri, 13 Nov 2026 06:07:20 +0000 Subject: [PATCH 3/8] chore(laravel): add the posthog-laravel minor intent for the posthog mailer Co-Authored-By: Claude Opus 5.5 --- .changeset/fruity-frogs-relax.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/fruity-frogs-relax.md diff --git a/.changeset/fruity-frogs-relax.md b/.changeset/fruity-frogs-relax.md new file mode 100644 index 00000000..afc116b8 --- /dev/null +++ b/.changeset/fruity-frogs-relax.md @@ -0,0 +1,5 @@ +--- +"posthog-laravel": minor +--- + +Send Mailables and mail notifications through PostHog: add a mailer with `'transport' => 'posthog'` in `config/mail.php` and set `MAIL_MAILER=posthog`. Each mail sends under its Mailable or notification class in kebab case as its template key, also through failover, round-robin and on-demand mailers; `X-PostHog-*` headers set the template key, distinct ID and idempotency key. Templates made in PostHog are not supported. From db4b2d15d602b54e2f7f05c5aea7d026637fe348 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Fri, 13 Nov 2026 07:03:00 +0000 Subject: [PATCH 4/8] fix(laravel): send mail that reads like an earlier one under its own template key A failover or round-robin mailer hands the transport a clone, which the driver matched to the first equal mail it had named. When the app still held an earlier mail with the same content, the new mail sent under the earlier class's key, and a mail with no class took that key over the mailer's default. The driver now names every mail, classless ones too, and takes the newest equal one: Laravel names a mail just before its transport sends it. The derived key now goes to the core transport as its default template key instead of a header on the mail; the core keeps an explicit X-PostHog-Template-Key first. Co-Authored-By: Claude Opus 5.5 --- packages/laravel/src/Mail/MailDriver.php | 47 ++++++++----------- .../laravel/tests/Fixtures/ShipmentUpdate.php | 8 ++++ packages/laravel/tests/MailDriverTest.php | 37 +++++++++++++++ 3 files changed, 65 insertions(+), 27 deletions(-) create mode 100644 packages/laravel/tests/Fixtures/ShipmentUpdate.php diff --git a/packages/laravel/src/Mail/MailDriver.php b/packages/laravel/src/Mail/MailDriver.php index 0df5022b..9de4f5d4 100644 --- a/packages/laravel/src/Mail/MailDriver.php +++ b/packages/laravel/src/Mail/MailDriver.php @@ -11,7 +11,6 @@ use Symfony\Component\Mailer\Envelope; use Symfony\Component\Mailer\SentMessage; use Symfony\Component\Mailer\Transport\TransportInterface; -use Symfony\Component\Mime\Message; use Symfony\Component\Mime\RawMessage; use WeakMap; @@ -27,11 +26,10 @@ final class MailDriver implements TransportInterface { private const INTEGRATION = 'laravel'; - private const TEMPLATE_KEY = 'X-PostHog-Template-Key'; // The longest template key the send API takes. private const TEMPLATE_KEY_LENGTH = 256; - /** @var WeakMap|null The template key of each mail Laravel is sending. */ + /** @var WeakMap|null The class-name key of each mail Laravel sends, or '' for mail with no class. */ private static ?WeakMap $templateKeys = null; private function __construct(private readonly ?string $defaultTemplateKey) @@ -53,30 +51,23 @@ public static function extend(MailManager $manager): void public static function nameTheMail(MessageSending $event): void { $class = $event->data['__laravel_mailable'] ?? $event->data['__laravel_notification'] ?? null; - if (!is_string($class)) { - return; - } - $key = preg_replace('/[^a-zA-Z0-9_-]+/', '-', Str::kebab(class_basename($class))); - $key = substr(trim((string) $key, '-'), 0, self::TEMPLATE_KEY_LENGTH); - if ($key !== '') { - self::$templateKeys ??= new WeakMap(); - self::$templateKeys[$event->message] = $key; + $key = ''; + if (is_string($class)) { + $key = (string) preg_replace('/[^a-zA-Z0-9_-]+/', '-', Str::kebab(class_basename($class))); + $key = substr(trim($key, '-'), 0, self::TEMPLATE_KEY_LENGTH); } + self::$templateKeys ??= new WeakMap(); + self::$templateKeys[$event->message] = $key; } public function send(RawMessage $message, ?Envelope $envelope = null): ?SentMessage { - $key = self::templateKeyOf($message); - if ($key !== null && $message instanceof Message && !$message->getHeaders()->has(self::TEMPLATE_KEY)) { - // PostHogTransport reads the reserved header and strips it, so it never goes out. - $message->getHeaders()->addTextHeader(self::TEMPLATE_KEY, $key); - } - - // Built per send, so each request, job or Octane worker sends with its own scoped client. + // Built per send, so each request, job or Octane worker sends with its own scoped client. The core + // transport still gives an `X-PostHog-Template-Key` header on the mail precedence over this key. $transport = new PostHogTransport( Container::getInstance()->make(PostHog::class)->client()->emails(), integration: self::INTEGRATION . '/' . PostHog::VERSION, - defaultTemplateKey: $this->defaultTemplateKey, + defaultTemplateKey: self::templateKeyOf($message) ?? $this->defaultTemplateKey, templates: false, ); @@ -88,17 +79,19 @@ private static function templateKeyOf(RawMessage $message): ?string if (self::$templateKeys === null) { return null; } - if (isset(self::$templateKeys[$message])) { - return self::$templateKeys[$message]; - } - // A failover or round-robin mailer sends each transport a clone of the mail, equal to it until sent. - foreach (self::$templateKeys as $mail => $key) { - if ($mail == $message) { - return $key; + $match = self::$templateKeys[$message] ?? null; + if ($match === null) { + // A failover or round-robin mailer sends each transport a clone of the mail, equal to it until sent. + // Laravel names each mail just before its transport sends it, so of the equal mails an app still + // holds, the one named last is the one being sent. + foreach (self::$templateKeys as $mail => $key) { + if ($mail == $message) { + $match = $key; + } } } - return null; + return $match === '' ? null : $match; } public function __toString(): string diff --git a/packages/laravel/tests/Fixtures/ShipmentUpdate.php b/packages/laravel/tests/Fixtures/ShipmentUpdate.php new file mode 100644 index 00000000..7f1be476 --- /dev/null +++ b/packages/laravel/tests/Fixtures/ShipmentUpdate.php @@ -0,0 +1,8 @@ +assertSame('order-shipped', $this->templateKeyOfOnlySend()); } + public function testTwoMailablesThatReadAlikeSendUnderTheirOwnClassNamesThroughAFailoverMailer(): void + { + $this->app['config']->set('mail.mailers.failover', self::FAILOVER); + $this->sendApi([self::SENT, self::SENT]); + + // The app keeps the first sent mail, as a log or an event listener might. + $first = Mail::mailer('failover')->to('ana@example.com')->send(new OrderShipped()); + Mail::mailer('failover')->to('ana@example.com')->send(new ShipmentUpdate()); + + $keys = array_map( + fn(array $request) => json_decode($request['body'], true)['template_key'], + $this->api->requests() + ); + $this->assertSame(['order-shipped', 'shipment-update'], $keys); + $this->assertNotNull($first); + } + + public function testMailWithNoClassThatReadsLikeAnEarlierMailableSendsUnderTheDefaultTemplateKey(): void + { + $this->app['config']->set('mail.mailers.posthog.default_template_key', 'receipts'); + $this->app['config']->set('mail.mailers.failover', self::FAILOVER); + $this->sendApi([self::SENT, self::SENT]); + + $first = Mail::mailer('failover')->to('ana@example.com')->send(new OrderShipped()); + Mail::mailer('failover')->html('

On its way.

', function ($message) { + $message->from('shop@example.com')->to('ana@example.com')->subject('Your order shipped'); + }); + + $keys = array_map( + fn(array $request) => json_decode($request['body'], true)['template_key'], + $this->api->requests() + ); + $this->assertSame(['order-shipped', 'receipts'], $keys); + $this->assertNotNull($first); + } + public function testAMailableSendsUnderItsClassNameThroughAMailerBuiltOnDemand(): void { $this->sendApi(); From 9d73bb4c2d209c705e09445c797280ed23c40176 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Fri, 13 Nov 2026 07:30:31 +0000 Subject: [PATCH 5/8] fix(laravel): name a failover mail by the mail Laravel sent, and refuse a bad default key up front A failover or round-robin mailer hands the PostHog transport a clone of the mail, which the driver matched to the newest equal mail it had named. A listener that sent an equal mail while another was sending gave the outer mail the inner one's key. Laravel's envelope, which Symfony hands every transport of the mailer, holds the mail Laravel named, so the driver now looks the key up by that mail and matches nothing by content. Since mail with a class sends under its own key, a default_template_key the send API rejects failed only mail without one. The mailer now refuses that key when it is built. Co-Authored-By: Claude Opus 5.5 --- packages/laravel/src/Mail/MailDriver.php | 75 +++++++++++++---------- packages/laravel/tests/MailDriverTest.php | 43 +++++++++++++ 2 files changed, 87 insertions(+), 31 deletions(-) diff --git a/packages/laravel/src/Mail/MailDriver.php b/packages/laravel/src/Mail/MailDriver.php index 9de4f5d4..588eff23 100644 --- a/packages/laravel/src/Mail/MailDriver.php +++ b/packages/laravel/src/Mail/MailDriver.php @@ -6,8 +6,10 @@ use Illuminate\Mail\Events\MessageSending; use Illuminate\Mail\MailManager; use Illuminate\Support\Str; +use InvalidArgumentException; use PostHog\Laravel\PostHog; use PostHog\Mailer\PostHogTransport; +use Symfony\Component\Mailer\DelayedEnvelope; use Symfony\Component\Mailer\Envelope; use Symfony\Component\Mailer\SentMessage; use Symfony\Component\Mailer\Transport\TransportInterface; @@ -26,14 +28,20 @@ final class MailDriver implements TransportInterface { private const INTEGRATION = 'laravel'; - // The longest template key the send API takes. private const TEMPLATE_KEY_LENGTH = 256; + private const NOT_IN_A_TEMPLATE_KEY = '/[^a-zA-Z0-9_-]+/'; - /** @var WeakMap|null The class-name key of each mail Laravel sends, or '' for mail with no class. */ + /** @var WeakMap|null The class-name key of each mail Laravel sends. */ private static ?WeakMap $templateKeys = null; private function __construct(private readonly ?string $defaultTemplateKey) { + if ($defaultTemplateKey !== null && !self::isTemplateKey($defaultTemplateKey)) { + throw new InvalidArgumentException( + 'The default template key can only have letters, digits, hyphens (-) and underscores (_), at most ' + . self::TEMPLATE_KEY_LENGTH . '.' + ); + } } public static function extend(MailManager $manager): void @@ -51,47 +59,52 @@ public static function extend(MailManager $manager): void public static function nameTheMail(MessageSending $event): void { $class = $event->data['__laravel_mailable'] ?? $event->data['__laravel_notification'] ?? null; - $key = ''; - if (is_string($class)) { - $key = (string) preg_replace('/[^a-zA-Z0-9_-]+/', '-', Str::kebab(class_basename($class))); - $key = substr(trim($key, '-'), 0, self::TEMPLATE_KEY_LENGTH); + if (!is_string($class)) { + return; + } + $key = (string) preg_replace(self::NOT_IN_A_TEMPLATE_KEY, '-', Str::kebab(class_basename($class))); + $key = substr(trim($key, '-'), 0, self::TEMPLATE_KEY_LENGTH); + if ($key !== '') { + self::$templateKeys ??= new WeakMap(); + self::$templateKeys[$event->message] = $key; } - self::$templateKeys ??= new WeakMap(); - self::$templateKeys[$event->message] = $key; } public function send(RawMessage $message, ?Envelope $envelope = null): ?SentMessage { - // Built per send, so each request, job or Octane worker sends with its own scoped client. The core - // transport still gives an `X-PostHog-Template-Key` header on the mail precedence over this key. - $transport = new PostHogTransport( - Container::getInstance()->make(PostHog::class)->client()->emails(), - integration: self::INTEGRATION . '/' . PostHog::VERSION, - defaultTemplateKey: self::templateKeyOf($message) ?? $this->defaultTemplateKey, - templates: false, - ); + $mail = $this->mailLaravelHandedOver($envelope) ?? $message; - return $transport->send($message, $envelope); + return $this->transportForThisSend(self::$templateKeys[$mail] ?? $this->defaultTemplateKey) + ->send($message, $envelope); } - private static function templateKeyOf(RawMessage $message): ?string + /** + * A failover or round-robin mailer hands each transport a clone of the mail with Laravel's own envelope, + * which holds the mail Laravel named. + */ + private function mailLaravelHandedOver(?Envelope $envelope): ?RawMessage { - if (self::$templateKeys === null) { + if (!$envelope instanceof DelayedEnvelope) { return null; } - $match = self::$templateKeys[$message] ?? null; - if ($match === null) { - // A failover or round-robin mailer sends each transport a clone of the mail, equal to it until sent. - // Laravel names each mail just before its transport sends it, so of the equal mails an app still - // holds, the one named last is the one being sent. - foreach (self::$templateKeys as $mail => $key) { - if ($mail == $message) { - $match = $key; - } - } - } - return $match === '' ? null : $match; + return (fn(): ?RawMessage => $this->message ?? null)->call($envelope); + } + + private function transportForThisSend(?string $templateKey): PostHogTransport + { + return new PostHogTransport( + Container::getInstance()->make(PostHog::class)->client()->emails(), + integration: self::INTEGRATION . '/' . PostHog::VERSION, + defaultTemplateKey: $templateKey, + templates: false, + ); + } + + private static function isTemplateKey(string $key): bool + { + return $key !== '' && strlen($key) <= self::TEMPLATE_KEY_LENGTH + && preg_match(self::NOT_IN_A_TEMPLATE_KEY, $key) !== 1; } public function __toString(): string diff --git a/packages/laravel/tests/MailDriverTest.php b/packages/laravel/tests/MailDriverTest.php index 735b2a32..f0df934e 100644 --- a/packages/laravel/tests/MailDriverTest.php +++ b/packages/laravel/tests/MailDriverTest.php @@ -2,12 +2,15 @@ namespace PostHog\Laravel\Tests; +use Illuminate\Mail\Events\MessageSending; use Illuminate\Mail\Events\MessageSent; use Illuminate\Notifications\AnonymousNotifiable; use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Notification; +use InvalidArgumentException; use Orchestra\Testbench\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; use PostHog\Laravel\Facades\PostHog as PostHogFacade; use PostHog\Laravel\PostHog; use PostHog\Laravel\PostHogServiceProvider; @@ -154,6 +157,46 @@ public function testMailWithNoClassThatReadsLikeAnEarlierMailableSendsUnderTheDe $this->assertNotNull($first); } + public function testAMailSentWhileAnotherIsSendingLeavesTheOtherItsClassName(): void + { + $this->app['config']->set('mail.mailers.failover', self::FAILOVER); + $this->sendApi(); + $archived = null; + Event::listen(MessageSending::class, function (MessageSending $event) use (&$archived) { + if ($archived === null && ($event->data['__laravel_mailable'] ?? null) === OrderShipped::class) { + $archived = Mail::mailer('archive')->to('ana@example.com')->send(new ShipmentUpdate()); + } + }); + + Mail::mailer('failover')->to('ana@example.com')->send(new OrderShipped()); + + $this->assertNotNull($archived); + $this->assertSame('order-shipped', $this->templateKeyOfOnlySend()); + } + + /** + * @return array + */ + public static function templateKeysTheSendApiRejects(): array + { + return ['a space' => ['App mail'], 'empty' => [''], 'too long' => [str_repeat('a', 257)]]; + } + + #[DataProvider('templateKeysTheSendApiRejects')] + public function testAMailerWithADefaultTemplateKeyTheSendApiRejectsIsRefusedForEveryMail(string $key): void + { + $this->app['config']->set('mail.mailers.posthog.default_template_key', $key); + $this->sendApi(); + + try { + Mail::to('ana@example.com')->send(new OrderShipped()); + $this->fail('A mailer with an invalid default template key sent.'); + } catch (InvalidArgumentException $refusal) { + $this->assertStringContainsString('default template key', $refusal->getMessage()); + } + $this->assertSame([], $this->api->requests()); + } + public function testAMailableSendsUnderItsClassNameThroughAMailerBuiltOnDemand(): void { $this->sendApi(); From 999420b10c098cb1ca0e6434f9a2cbf529accec8 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Fri, 13 Nov 2026 07:37:48 +0000 Subject: [PATCH 6/8] refactor(laravel): check the default template key with the core's rule The mailer checked default_template_key against its own copy of the send API's template key rule. It now uses the core mapper's pattern, which moves with the exact core version posthog-laravel pins, and the README says which characters the key takes. Co-Authored-By: Claude Opus 5.5 --- packages/laravel/README.md | 2 +- packages/laravel/src/Mail/MailDriver.php | 9 ++------- 2 files changed, 3 insertions(+), 8 deletions(-) diff --git a/packages/laravel/README.md b/packages/laravel/README.md index 19c7fe1b..90561f78 100644 --- a/packages/laravel/README.md +++ b/packages/laravel/README.md @@ -314,7 +314,7 @@ API. It needs `POSTHOG_API_KEY` and the project secret key in `POSTHOG_SECRET_KE 'mailers' => [ 'posthog' => [ 'transport' => 'posthog', - // Optional: the template key of mail that has no class, such as Mail::raw(). + // Optional: the template key (letters, digits, - and _) of mail that has no class, such as Mail::raw(). 'default_template_key' => 'app-mail', ], ], diff --git a/packages/laravel/src/Mail/MailDriver.php b/packages/laravel/src/Mail/MailDriver.php index 588eff23..910893d9 100644 --- a/packages/laravel/src/Mail/MailDriver.php +++ b/packages/laravel/src/Mail/MailDriver.php @@ -7,6 +7,7 @@ use Illuminate\Mail\MailManager; use Illuminate\Support\Str; use InvalidArgumentException; +use PostHog\Internal\Mailer\EmailMapper; use PostHog\Laravel\PostHog; use PostHog\Mailer\PostHogTransport; use Symfony\Component\Mailer\DelayedEnvelope; @@ -36,7 +37,7 @@ final class MailDriver implements TransportInterface private function __construct(private readonly ?string $defaultTemplateKey) { - if ($defaultTemplateKey !== null && !self::isTemplateKey($defaultTemplateKey)) { + if ($defaultTemplateKey !== null && preg_match(EmailMapper::TEMPLATE_KEY_PATTERN, $defaultTemplateKey) !== 1) { throw new InvalidArgumentException( 'The default template key can only have letters, digits, hyphens (-) and underscores (_), at most ' . self::TEMPLATE_KEY_LENGTH . '.' @@ -101,12 +102,6 @@ private function transportForThisSend(?string $templateKey): PostHogTransport ); } - private static function isTemplateKey(string $key): bool - { - return $key !== '' && strlen($key) <= self::TEMPLATE_KEY_LENGTH - && preg_match(self::NOT_IN_A_TEMPLATE_KEY, $key) !== 1; - } - public function __toString(): string { return 'posthog'; From a31e8581dd95e3755391aa00f0345184acaf9f33 Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Fri, 13 Nov 2026 07:41:13 +0000 Subject: [PATCH 7/8] docs(laravel): give the default template key's length Co-Authored-By: Claude Opus 5.5 --- packages/laravel/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/laravel/README.md b/packages/laravel/README.md index 90561f78..7382a64c 100644 --- a/packages/laravel/README.md +++ b/packages/laravel/README.md @@ -314,7 +314,8 @@ API. It needs `POSTHOG_API_KEY` and the project secret key in `POSTHOG_SECRET_KE 'mailers' => [ 'posthog' => [ 'transport' => 'posthog', - // Optional: the template key (letters, digits, - and _) of mail that has no class, such as Mail::raw(). + // Optional: the template key of mail that has no class, such as Mail::raw(): + // 1 to 256 letters, digits, - and _. 'default_template_key' => 'app-mail', ], ], From e41fc2c036ec353d6c53aa995ce1f49110640b4a Mon Sep 17 00:00:00 2001 From: "Reichenbach, Michael" <755327+Silthus@users.noreply.github.com> Date: Fri, 13 Nov 2026 07:56:54 +0000 Subject: [PATCH 8/8] fix(laravel): keep PostHog headers off mail a failover hands to the next mailer A Mailable sets its PostHog options, such as X-PostHog-Distinct-Id and X-PostHog-Idempotency-Key, as headers. When the PostHog send failed, a failover mailer handed the next transport, such as SMTP, a clone of the mail with those headers still on it, so the recipient got them. Once PostHog has tried a mail, the driver now removes its X-PostHog-* headers from the mail Laravel handed over. Co-Authored-By: Claude Opus 5.5 --- packages/laravel/src/Mail/MailDriver.php | 26 +++++++++++++++++++---- packages/laravel/tests/MailDriverTest.php | 8 +++++-- 2 files changed, 28 insertions(+), 6 deletions(-) diff --git a/packages/laravel/src/Mail/MailDriver.php b/packages/laravel/src/Mail/MailDriver.php index 910893d9..b16975e7 100644 --- a/packages/laravel/src/Mail/MailDriver.php +++ b/packages/laravel/src/Mail/MailDriver.php @@ -14,6 +14,7 @@ use Symfony\Component\Mailer\Envelope; use Symfony\Component\Mailer\SentMessage; use Symfony\Component\Mailer\Transport\TransportInterface; +use Symfony\Component\Mime\Message; use Symfony\Component\Mime\RawMessage; use WeakMap; @@ -25,12 +26,15 @@ * Each mail sends under its Mailable or notification class in kebab case as its template key, so * `App\Mail\OrderShipped` sends as `order-shipped`. An `X-PostHog-Template-Key` header on the mail wins; * mail with no class, such as `Mail::raw()`, uses the mailer's `default_template_key`, or `laravel`. + * Once PostHog has tried a mail, its `X-PostHog-*` headers are gone, so the next mailer of a failover + * never sends them. */ final class MailDriver implements TransportInterface { private const INTEGRATION = 'laravel'; private const TEMPLATE_KEY_LENGTH = 256; private const NOT_IN_A_TEMPLATE_KEY = '/[^a-zA-Z0-9_-]+/'; + private const POSTHOG_HEADER = 'x-posthog-'; /** @var WeakMap|null The class-name key of each mail Laravel sends. */ private static ?WeakMap $templateKeys = null; @@ -54,8 +58,7 @@ public static function extend(MailManager $manager): void } /** - * Remembers the mail's class as its template key for the PostHog transport. The mail itself is left as is, - * so no other transport, such as the next one of a failover mailer, sends a PostHog header. + * Remembers the mail's class as its template key for the PostHog transport, without a header on the mail. */ public static function nameTheMail(MessageSending $event): void { @@ -74,9 +77,24 @@ public static function nameTheMail(MessageSending $event): void public function send(RawMessage $message, ?Envelope $envelope = null): ?SentMessage { $mail = $this->mailLaravelHandedOver($envelope) ?? $message; + try { + return $this->transportForThisSend(self::$templateKeys[$mail] ?? $this->defaultTemplateKey) + ->send($message, $envelope); + } finally { + self::removePostHogHeaders($mail); + } + } - return $this->transportForThisSend(self::$templateKeys[$mail] ?? $this->defaultTemplateKey) - ->send($message, $envelope); + private static function removePostHogHeaders(RawMessage $mail): void + { + if (!$mail instanceof Message) { + return; + } + foreach ($mail->getHeaders()->getNames() as $name) { + if (str_starts_with($name, self::POSTHOG_HEADER)) { + $mail->getHeaders()->remove($name); + } + } } /** diff --git a/packages/laravel/tests/MailDriverTest.php b/packages/laravel/tests/MailDriverTest.php index f0df934e..3c507625 100644 --- a/packages/laravel/tests/MailDriverTest.php +++ b/packages/laravel/tests/MailDriverTest.php @@ -219,11 +219,15 @@ public function testAMailableFailingOverFromPostHogReachesTheNextMailerWithoutPo $sent[] = $event->message; }); - Mail::mailer('failover')->to('ana@example.com')->send(new OrderShipped()); + Mail::mailer('failover')->to('ana@example.com')->send(new OrderShipped([ + 'X-PostHog-Distinct-Id' => 'user_123', + 'X-PostHog-Idempotency-Key' => 'order-42:order-shipped', + ])); $this->assertCount(1, $this->api->requests()); $this->assertCount(1, $sent); - $this->assertFalse($sent[0]->getHeaders()->has('X-PostHog-Template-Key')); + $headers = $sent[0]->getHeaders()->getNames(); + $this->assertSame([], array_values(preg_grep('/^x-posthog-/i', $headers))); } public function testAnotherMailerSendsTheMailableWithoutPostHogHeaders(): void