DEV Community

Cover image for Laravel MailGun with template, tags, and variables
Yurich
Yurich

Posted on • Updated on

Laravel MailGun with template, tags, and variables

Laravel is a great framework with a large ecosystem. There you can find tools for various services. But sometimes official libraries, and even more so unofficial ones, do not have all the functionality we need.

Mailgun is one of the popular email services and Laravel has a driver to use this service. Although Mailgun has a powerful tool for managing templates, such an option is not included in the library.
I found other libraries on the Internet that offer work with templates, but I wanted to work with the official library and use Mail class. That's why I decided to add the create Mailgun trait that expands the capabilities of the library.

namespace App\Traits;

trait Mailgun
{
   public function template($name = 'general'): self
   {
       return $this->withSymfonyMessage(function ($message) use ($name) {
           $message->getHeaders()->addTextHeader('X-Mailgun-Template-Name', $name);
       });
   }

   public function variable($name, $value): self
   {
       return $this->withSymfonyMessage(function ($message) use ($name, $value) {
           $message->getHeaders()->addTextHeader('X-Mailgun-Variables', json_encode([$name => $value]));
       });
   }

   public function tag($name): self
   {
       return $this->withSymfonyMessage(function ($message) use ($name) {
           $message->getHeaders()->addTextHeader('X-Mailgun-Tag', $name);
       });
   }
}
Enter fullscreen mode Exit fullscreen mode

Connect this trait to the mail class and now we have the template, tag, and variable methods available.

class MessageMail extends Mailable implements ShouldQueue
{
   use Queueable, SerializesModels, Mailgun;

   /**
    * Create a new message instance.
    *
    * @return void
    */
   public function __construct(
       private User $user,
   )
   {
   }

   /**
    * Build the message.
    *
    * @return $this
    */
   public function build()
   {
       return $this
           ->subject('Email Subject')
           ->to($this->user->email)
           ->html('')
           ->tag('my_custom_tag')
           ->template('mailgun_template')
           ->variable('name', $this->user->name)
           ->variable('link', config('app.url'))
           ->variable('email', $this->user->email);
   }
}
Enter fullscreen mode Exit fullscreen mode

I hope that soon such an opportunity will appear out of the box. Or I finally send a Pull Request.

Top comments (1)

Collapse
 
kutluk profile image
kutluk

Clean solution. Thank you Yurich!