blog, Website Design

Using Mailgun with Lumen

As the lead for a major API project I’ve been digging into Lumen (the stunningly fast micro-framework by Laravel).  Because we already had Mailgun setup for another Laravel project at work I decided to use it for the API project.

My starting point was the mail documentation on the Lumen website(https://lumen.laravel.com/docs/5.7/mail).  This documentation was very brief and not much help.  Then I dug into the PHP document on the Mailgun website (https://documentation.mailgun.com/en/latest/api-sending.html) and this didn’t prove incredibly useful either.  Like any good developer I then turned to copious searches on Google and reading lots of horrible work-around solutions.  I followed a few, but they all seemed overly complicated.

Then something clicked.  I had been using Couchbase with Lumen and it was easy to incorporate the PHP SDK.  Why not copy the same implementation I had for Couchbase with the Mailgun SDK?

First there were some requirements.  The server was running Ubuntu 16.04 so using Composer with a terminal connection  to the project root  I installed the SDK and required dependencies.

composer require mailgun/mailgun-php php-http/curl-client guzzlehttp/psr7

Then I created a new controller and named it MailgunController.php

At the top of the file, under the namespace I told the controller to use Illuminate and Mailgun.

use Illuminate\Http\Request;
use Mailgun\Mailgun;

Then opening the .env file for the project added a few lines:

MAILGUN_DOMAIN=sandbox#######.mailgun.org
MAILGUN_SECRET=MyMailgunApiKey

The next step was to create a public function in the MailgunController to send a test message:

public function emailTest(Request $request) {
  $subject = $request->subject;
  $htmlBody = view('email.BasicReply');
  $to = $request->recipient;
  $from = $request->from;
  // authenticate Mailgun
  $mgClient = new Mailgun(env("MAILGUN_SECRET"));
  $domain = env("MAILGUN_DOMAIN");

  // build email with open tracking
  $emailData = array(
    'from' => $from,
    'to' => $to,
    'subject' => $subject,
    'html' => $htmlBody,
    'o:tracking' => true
  );
  // Make the call to the Mailgun client.
  $result = $mgClient->sendMessage($domain, $emailData);

  return json_encode($result);
}

To test this in Postman I needed to have a route:

$router->post('email/send/v1', 'MailgunController@emailTest');

I tested this in Postman and everything worked.  This was WAY easier than anything I had read online having researched it for a day or two.

Note:  image was taken from the Mailgun blog

Leave a Reply