Lazy Tagging Outgoing Email

Lazy Tagging Outgoing Email
Photo by Angèle Kamp / Unsplash

I used to send my transactional email using AWS SES, but more recently - due some annoying problem with the access to AWS - I moved away to land on SendInBlue. Good service, based in Europe (GDPR FTW!), already integrated with the Symfony Mailer - and, by extension, with Laravel.

One main issue with SendInBlue is error handling based on webhooks: as AWS SES is integrated with AWS SNS and it is possible to setup different hooks for each enabled email address, SendInBlue delivers every webhook notification to every given URL with no distinctions among involved addresses. And, as I use my account for different services (would be a bit expensive, otherwise), I had to find some method to sort those notifications due context.

It is possible to attach a tag to emails, and retrieve it in webhook notifications so to distinguish the different sources, but I had no intention to review my (many) mail generation code to add a tag to each. So, I've used the MessageSending event generated by Laravel to intercept all outgoing mail and alter them just before actual delivery.

In EventServiceProvider I've added:

use Illuminate\Mail\Events\MessageSending;
use App\Listeners\CustomMailTag;

protected $listen = [
  MessageSending::class => [
    CustomMailTag::class
  ],
];

then I've created a listener in app/Listeners/CustomMailTag.php

<?php

namespace App\Listeners;

use Illuminate\Mail\Events\MessageSending;
use Symfony\Component\Mailer\Header\TagHeader;

class CustomMailTag
{
  public function handle(MessageSending $event)
  {
    $event->message->getHeaders()->add(new TagHeader('myowntag'));
    return true;
  }
}

So, every outgoing email has the myowntag attached, and the Controller's function assigned to my webhook URL looks like:

public function postStatusSendinblue(Request $request)
{
  if (in_array('myowntag', $request->input('tags'))) {
    /* handling code */
  }
}

This do not solve the - subjective - problem to deliver all webhook notifications to all intended applications, just to drop most of them (as each application would drop all notifications with a tag different to the assegned one): sooner or later I will eventually implement some kind of single hub to dispatch each notification to each intended application, and only to it.