Lumen 6 & Laravel Mail using Mailgun

Nahuel Bulian
2 min readDec 29, 2019

--

This is a simple guide to setup Lumen 6 with Mailgun.

This tutorial assumes that you already created a new project.

1. Require illuminate/mail

Run this command in your root level of application.

composer require illuminate/mail

2. Require guzzlehttp/guzzle

The API based drivers such as Mailgun and Postmark require the Guzzle HTTP library.

composer require guzzlehttp/guzzle

3. Create the configuration files

Create a new folder at the root level of application called config (if it doesn’t already exist). In this folder create two new files, one named mail.php and another named services.php.

You can copy the files content directly from the Laravel repository.

https://github.com/laravel/laravel/blob/master/config/mail.php

Into the mail.php change set the driver to mailgun:

'driver' => env('MAIL_DRIVER', 'mailgun'),

The next file don’t need any modification, you can copy it as is.

https://github.com/laravel/laravel/blob/master/config/services.php

4. Set up Lumen bootstrap/app.php

Uncomment the following line into the file app.php:

$app->withFacades();

Into the same file in section “Register Service Providers” add the the following line:

$app->register(Illuminate\Mail\MailServiceProvider::class);

Also add this lines to load the customs configuration files in config.

$app->configure('mail');
$app->configure('services');

5. And finally add the following to your .env file

Remember to use your mailgun credentials in the .env file.

MAIL_DRIVER=mailgun
MAILGUN_DOMAIN=<your-mailgun-domain>
MAILGUN_SECRET=<your-mailgun-api-key>

6. Now you are able to start sending emails

Let’s try it, add the following line into your routes/web.php file.

$router->get('/send-email', 'EmailController@sendEmail');

Now create a controller named EmailController.php into app/Http/Controllers/ folder with the followin code:

<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Mail;
use App\Http\Controllers\Controller;
class EmailController extends Controller
{
public function sendEmail()
{
Mail::raw('This is the email body.', function ($message) {
$message->to('username@domain.com')
->subject('Lumen email test');
});
if (Mail::failures()) {
return 'Sorry! Please try again latter :(';
} else {
return 'Great! eMail successfully sent ;)';
}
}
}

In the console run your local development server:

php -S localhost:8000 -t public

Visit the following url in your browser:

http://localhost:8000/send-email

If everything goes well you’ll see this message in your browser:

Great! eMail successfully sent ;)

And receive an email like this in your inbox:

For more information visit the official Lumen documentation.

That’s it! Enjoy sending emails from your Lumen application!

--

--

Nahuel Bulian
Nahuel Bulian

Written by Nahuel Bulian

#Entrepreneur, tech developer & #crypto enthusiast #bitcoin #ethereum

Responses (1)