0

As you know many e-mail providers have the feature to use e-mail templates. Through their API you can send e-mails, just by setting the template id and passing through the variables. The predefined template will be send to the user.

For my project I want to use Mailjet API for transactional e-mails. What is the best way to call their email API in my project. Because laravel already has lots of email and notification features so I am looking for the best practice to integrate this in my project.

For example I want so make use of notifications. This notification has to call the mailjet email api and pass through the template id and the needed variables. What is the best way to archive this. With a custom notification channel maybe?

Or are there other good alternatives?

Jochem Gruter
  • 2,813
  • 5
  • 21
  • 43

1 Answers1

0

You are right, you can use an alternative mailing service while using Laravel's neat notifications feature. You will need to create a custom notification channel where you can define sending logic by hitting Mailjet's API endpoints. When the notification channel is all set up, you can specify it inside a notification itself where you can define the exact request body.

To make things easier, you may use Mailjet's official PHP wrapper so you don't have to work with raw HTTP requests.

Personally I used the same technique for Twilio SMS and Nexmo (Vonage) SMS Verification codes. I will add some of my code so you can see how I organised things:

class PhoneChannel
{
    public function send($notifiable, Notification $notification)
    {
        if ($notification->resend) {
            $this->repeatCall();
        } else {
            $this->initCall();
        }
    }

    ...
class VerifyPhone extends Notification
{
    use Queueable;

    public bool $resend;

    public function __construct(bool $resend)
    {
        $this->resend = $resend;
    }

    public function via($notifiable): array
    {
        return [PhoneChannel::class];
    }
}

The point is that you can define a request body inside the notification itself in order to access it later in the notification channel. Just add a method called toMailjet inside a notification, specify your variables, and then access it inside a channel via $notification->toMailjet()

Andrii H.
  • 1,682
  • 3
  • 20
  • 40