Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to send emails with Lumen 5.4 and Mailgun

I've configured Lumen 5.4.6 to send emails with Mailgun. I saw several other answers but they were incomplete or had unnecessary statements or they were more complicated than needed.

I put below complete and detailed steps to get Lumen to work with Mailgun as easy and clean as I've found.

If you know an easier, cleaner, eleganter way, please add your answers and comments.

like image 786
AMS777 Avatar asked Nov 05 '17 16:11

AMS777


1 Answers

UPDATE: I'm developing an open source quick-start boilerplate Lumen project with some useful functionality out of the box like emailing as well as user register and login: https://github.com/AMS777/ams-bl

It can be used as a starting point for a JSON API Lumen project or as a reference for the steps described below. There you can find also some notes to test and preview emails on browsers.

Configure Lumen

Add Laravel's Composer packages on command line:

composer require illuminate/mail
composer require guzzlehttp/guzzle

I was using Lumen 5.4.6, so I had to install an old mail package:

composer require illuminate/mail:5.4.*

On file bootstrap/app.php add:

bootstrap/app.php: (At Register Service Providers section.)

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

bootstrap/app.php: (At the end of the file, above the return.)

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

If you want to use the easy interface Facades to send the email, you have to uncomment:

bootstrap/app.php: (Uncomment.)

$app->withFacades();

Create following files on your project:

  • config/mail.php
  • config/services.php

Copy and arrange the contents of Laravel's files:

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

Here I've changed the default mail driver to mailgun. username and password are not used with mailgun driver, they may be removed.

config/mail.php:

<?php
return [
    /*
    |--------------------------------------------------------------------------
    | Mail Driver
    |--------------------------------------------------------------------------
    |
    | Laravel supports both SMTP and PHP's "mail" function as drivers for the
    | sending of e-mail. You may specify which one you're using throughout
    | your application here. By default, Laravel is setup for SMTP mail.
    |
    | Supported: "smtp", "sendmail", "mailgun", "mandrill", "ses",
    |            "sparkpost", "log", "array"
    |
    */
    'driver' => env('MAIL_DRIVER', 'mailgun'),
    /*
    |--------------------------------------------------------------------------
    | SMTP Host Address
    |--------------------------------------------------------------------------
    |
    | Here you may provide the host address of the SMTP server used by your
    | applications. A default option is provided that is compatible with
    | the Mailgun mail service which will provide reliable deliveries.
    |
    */
    'host' => env('MAIL_HOST', 'smtp.mailgun.org'),
    /*
    |--------------------------------------------------------------------------
    | SMTP Host Port
    |--------------------------------------------------------------------------
    |
    | This is the SMTP port used by your application to deliver e-mails to
    | users of the application. Like the host we have set this value to
    | stay compatible with the Mailgun e-mail application by default.
    |
    */
    'port' => env('MAIL_PORT', 587),
    /*
    |--------------------------------------------------------------------------
    | Global "From" Address
    |--------------------------------------------------------------------------
    |
    | You may wish for all e-mails sent by your application to be sent from
    | the same address. Here, you may specify a name and address that is
    | used globally for all e-mails that are sent by your application.
    |
    */
    'from' => [
        'address' => env('MAIL_FROM_ADDRESS', '[email protected]'),
        'name' => env('MAIL_FROM_NAME', 'Example'),
    ],
    /*
    |--------------------------------------------------------------------------
    | E-Mail Encryption Protocol
    |--------------------------------------------------------------------------
    |
    | Here you may specify the encryption protocol that should be used when
    | the application send e-mail messages. A sensible default using the
    | transport layer security protocol should provide great security.
    |
    */
    'encryption' => env('MAIL_ENCRYPTION', 'tls'),
    /*
    |--------------------------------------------------------------------------
    | SMTP Server Username
    |--------------------------------------------------------------------------
    |
    | If your SMTP server requires a username for authentication, you should
    | set it here. This will get used to authenticate with your server on
    | connection. You may also set the "password" value below this one.
    |
    */
    'username' => env('MAIL_USERNAME'),
    'password' => env('MAIL_PASSWORD'),
    /*
    |--------------------------------------------------------------------------
    | Sendmail System Path
    |--------------------------------------------------------------------------
    |
    | When using the "sendmail" driver to send e-mails, we will need to know
    | the path to where Sendmail lives on this server. A default path has
    | been provided here, which will work well on most of your systems.
    |
    */
    'sendmail' => '/usr/sbin/sendmail -bs',
    /*
    |--------------------------------------------------------------------------
    | Markdown Mail Settings
    |--------------------------------------------------------------------------
    |
    | If you are using Markdown based email rendering, you may configure your
    | theme and component paths here, allowing you to customize the design
    | of the emails. Or, you may simply stick with the Laravel defaults!
    |
    */
    'markdown' => [
        'theme' => 'default',
        'paths' => [
            resource_path('views/vendor/mail'),
        ],
    ],
];

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

Here I've stripped unnecessary lines.

config/services.php:

<?php
return [
    /*
    |--------------------------------------------------------------------------
    | Third Party Services
    |--------------------------------------------------------------------------
    |
    | This file is for storing the credentials for third party services such
    | as Stripe, Mailgun, SparkPost and others. This file provides a sane
    | default location for this type of information, allowing packages
    | to have a conventional place to find your various credentials.
    |
    */
    'mailgun' => [
        'domain' => env('MAILGUN_DOMAIN'),
        'secret' => env('MAILGUN_SECRET'),
    ],
];

Then you'll need to set the environment variables on your .env file:

.env:

MAIL_DRIVER=mailgun
MAIL_HOST=smtp.mailgun.org
MAIL_PORT=587
MAIL_ENCRYPTION=tls
[email protected]
MAIL_FROM_NAME="Your email sender name"
MAILGUN_DOMAIN=sandbox_EXAMPLE.mailgun.org
MAILGUN_SECRET=key-EXAMPLE

Well, so far is the email functionality is ready on Lumen.

Create and send email in Lumen

Once the mail functionality is set up, the steps to create and send emails in Lumen are the same as in Laravel, and can be checked on its documentation:

https://laravel.com/docs/5.4/mail

To send an email in Lumen you need 3 files:

  • Mail class. Extends Mailable. Build the email from a view.
  • Email template. A view. May be html or Blade engine.
  • Class that uses the mail class and send an email.

This example of mail class only imports the packages required to build emails. If you want to use queues, you'll need to import more packages.

app/mail/RegisterConfirmationEmail.php:

<?php

namespace App\Mail;

use Illuminate\Mail\Mailable;

class RegisterConfirmation extends Mailable
{
    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('RegisterConfirmationEmail');
    }
}

Views were removed from Lumen at 5.2 version, but were recovered soon after. As of Lumen 5.4 views work, but there is no clue of it on the documentation.

The raw() function may be used if you don't want to use views.

resources/views/RegisterConfirmationEmail.blade.php:

<html>
    <body>
        <h1>Test</h1>
    </body>
</html>

The class that sends the email must import the mail class. Remember that this example uses the interface Facades, that must be enabled on bootstrap/app.php.

app/Http/Controllers/RegisterController.php:

<?php

namespace App\Http\Controllers;

use App\Mail\RegisterConfirmation;
use Illuminate\Support\Facades\Mail;

class RegisterController extends Controller
{
    public function sendRegisterConfirmationEmail()
    {
        Mail::to('[email protected]')->send(new RegisterConfirmation());
    }
}

Mailgun

On Mailgun you have to create an account with some data of yours and of your company.

Mailgun will ask for your mobile phone number to proceed with your account verification:

"To prevent abuse, Mailgun requires you to verify your account through the use of SMS."

For a development account it's not required credit card nor domain verification, but you'll need to authorize up to 5 email addresses.

You can use a sandbox domain provided by Mailgun.

like image 54
AMS777 Avatar answered Oct 16 '22 19:10

AMS777