Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/fruity-frogs-relax.md
Original file line number Diff line number Diff line change
@@ -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.
39 changes: 39 additions & 0 deletions packages/laravel/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -304,6 +304,45 @@ 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():
// 1 to 256 letters, digits, - and _.
'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: <code>` 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()`.

## Laravel Pennant

An optional read-only PostHog store supports Pennant boolean and variant reads.
Expand Down
127 changes: 127 additions & 0 deletions packages/laravel/src/Mail/MailDriver.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
<?php

namespace PostHog\Laravel\Mail;

use Illuminate\Container\Container;
use Illuminate\Mail\Events\MessageSending;
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;
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 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`.
* 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<object, string>|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 && 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 . '.'
);
}
}

public static function extend(MailManager $manager): void
{
$manager->extend(
'posthog',
static fn(array $config): self => new self($config['default_template_key'] ?? null)
);
}

/**
* 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
{
$class = $event->data['__laravel_mailable'] ?? $event->data['__laravel_notification'] ?? null;
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;
}
}

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);
Comment on lines +83 to +84

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 · Preserve idempotency metadata when retrying the same email

When a caller retries the same email object after a PostHogTransportException, this finally block has removed its X-PostHog-Idempotency-Key. The next send() generates a fresh key, so a timeout after PostHog accepted the first request results in duplicate delivery. Preserve the extracted options out of band across retries while keeping fallback headers clean.

}
}

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);
}
}
}

/**
* 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 (!$envelope instanceof DelayedEnvelope) {
return null;
}

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,
);
}

public function __toString(): string
{
return 'posthog';
}
}
6 changes: 6 additions & 0 deletions packages/laravel/src/PostHogServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 PostHog\Laravel\Jobs\DeliverEvents;
use Illuminate\Support\ServiceProvider;
Expand Down Expand Up @@ -92,6 +95,9 @@ public function boot(): void
$reporter->remember($event->exception, 'task', '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, 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();
Expand Down
19 changes: 19 additions & 0 deletions packages/laravel/tests/Fixtures/InvoicePaid.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
<?php

namespace PostHog\Laravel\Tests\Fixtures;

use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class InvoicePaid extends Notification
{
public function via(object $notifiable): array
{
return ['mail'];
}

public function toMail(object $notifiable): MailMessage
{
return (new MailMessage())->from('billing@example.com')->subject('Invoice paid')->line('Thanks!');
}
}
33 changes: 33 additions & 0 deletions packages/laravel/tests/Fixtures/OrderShipped.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

namespace PostHog\Laravel\Tests\Fixtures;

use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Mail\Mailables\Headers;

class OrderShipped extends Mailable
{
/**
* @param array<string, string> $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: '<p>On its way.</p>');
}

public function headers(): Headers
{
return new Headers(text: $this->headers);
}
}
8 changes: 8 additions & 0 deletions packages/laravel/tests/Fixtures/ShipmentUpdate.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?php

namespace PostHog\Laravel\Tests\Fixtures;

/** A second Mailable whose mail reads exactly like OrderShipped. */
class ShipmentUpdate extends OrderShipped
{
}
Loading
Loading