Repository navigation
feat(laravel): send Mailables through PostHog with the posthog mailer #319
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Silthus
wants to merge
11
commits into
feat/symfony-mailer-transport
from
feat/laravel-posthog-mail-driver
Closed
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
1e4355f
feat(laravel): send Mailables and mail notifications through PostHog …
Silthus 981e18b
Merge remote-tracking branch 'origin/feat/symfony-mailer-transport' i…
Silthus c61f0d6
fix(laravel): name mail sent through failover and on-demand mailers, …
Silthus 6eba852
chore(laravel): add the posthog-laravel minor intent for the posthog …
Silthus db4b2d1
fix(laravel): send mail that reads like an earlier one under its own …
Silthus 37e6cf4
Merge remote-tracking branch 'origin/feat/symfony-mailer-transport' i…
Silthus 9d73bb4
fix(laravel): name a failover mail by the mail Laravel sent, and refu…
Silthus 999420b
refactor(laravel): check the default template key with the core's rule
Silthus a31e858
docs(laravel): give the default template key's length
Silthus e41fc2c
fix(laravel): keep PostHog headers off mail a failover hands to the n…
Silthus 856c2eb
Merge remote-tracking branch 'origin/feat/symfony-mailer-transport' i…
Silthus File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| } | ||
| } | ||
|
|
||
| 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'; | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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!'); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| { | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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, thisfinallyblock has removed itsX-PostHog-Idempotency-Key. The nextsend()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.