How we send Mailgun template emails in Laravel

Dominic PrawnStar Bauer
3 min readSep 13, 2020

I’m currently working on a Laravel project where our client has decided on using Mailgun to handle emails. This is great considering Laravel has built in functionality that works well with Mailgun and other email providers.

However, as the integration is meant to be generic so that you can plug in multiple email providers you lose certain functionality that may be available in an email provider specific integration.

We really wanted to use Mailgun’s email templates which you don’t seem to be able to use via the usual Laravel email integration unfortunately :(

We thought all hope was lost — Photo by Aliyah Jamous on Unsplash

STEP IN!

Mailgun-PHP

Luckily for us Mailgun-PHP saved us!

Here’s how we started shooting out Mailgun template emails from Laravel.

  1. Install the following:
composer require mailgun/mailgun-php guzzlehttp/guzzle nyholm/psr7

NB: The Mailgun-PHP docs say to install kriswallsmith/buzz but it seems to cause an issue and the solution we found was to instead install guzzle.

2. Use Mailgun-PHP in your file:

use Mailgun\Mailgun;

3. Set up necessary config and functionality:

$mgClient = Mailgun::create(
env('MAILGUN_SECRET'), // Mailgun API Key
env('MAILGUN_ENDPOINT'),
);
$domain = env('MAILGUN_DOMAIN');

4. Set up the params you need:

$params = array(
'from' => 'mailgunner@50calibre.com',
'to' => 'person@somewhere.com',
'subject' => 'Roundhouse KICK',
'template' => 'showcase_mailgun_template',
'v:username' => 'RichyRoundhouse',
'v:company_name' => 'Bruski',
);

You can get more info on the params available to you here but the important one is template. This allows you to select a template that you have created from Mailgun that corresponds to the name of the template.

mailgun template names MUST match

Our template name is showcase_mailgun_template in Mailgun so our template should correspond to the same name.

5. Send the damn email :)!

$mgClient->messages()->send($domain, $params);

So all in all our function looks something like this:

<?phpuse Mailgun\Mailgun;
class SendMailGunTemplate {
private function sendMail( $username, $company_name)
{
$mgClient = Mailgun::create(
env('MAILGUN_SECRET'),
env('MAILGUN_ENDPOINT'),
);
$domain = env('MAILGUN_DOMAIN'); $params = array(
'from' => 'mailgunner@50calibre.com',
'to' => 'person@somewhere.com',
'subject' => 'Roundhouse KICK',
'template' => 'showcase_mailgun_template',
'v:username' => 'RichyRoundhouse',
'v:company_name' => 'Bruski',
);

$mgClient->messages()->send($domain, $params);
}
}

which appears in my inbox like this:

email from Mailgun

and the email looks like this:

which means this:

Happy Developer :)

--

--

Dominic PrawnStar Bauer

Slowly trying to piece the world together one idea at a time :).