Learning Management Platform for Written Tutorial Series.

Laravel 6 Sending Email

Laravel 6 Sending Email

Email is a very important component of modern web applications. When a user registers on a website, it might be a good idea to send them an email to confirm their email address. For an application that requires users to login, email comes in handy when you want to send them a password reset link. These are just some of the few example where sending email is a must.

In this tutorial, we are going to learn how to send email from a Laravel application. Laravel makes working with emails really easy.

Topic to be covered

In this tutorial, we will cover the following topics.

  • Introduction to SwiftMailer
  • Laravel Email Drivers
  • Laravel Email Configuration
  • Laravel Sending Email

Introduction to SwiftMailer

SwiftMailer is a Symfony component that Laravel uses to send emails. Laravel abstracts the functionality of SwiftMailer y providing easy to use classes that you can generate from the command line.

Laravel Email Drivers

Laravel supports a number of drivers for sending email. The below briefly describes the supported drivers

  • SMTP -- SMTP stands for Simple Mail Transfer Protocol. It's is a standard communication protocol for sending emails.
  • Sendmail -- this an open source mail transfer agent software that is popular on Linux based systems. In a nutshell, it's a Unix simplified implementation of the SMTP protocol.
  • Mailgun -- This is an online email API service.
  • Mandrill -- This is also an online email API service but for Mailchimp users.
  • SES -- SES stands for Simple Email Service and its provided by the company Amazon and it's a cloud based service for digital marketers and application developers.
  • SparkPost -- This is an online Email Delivery and Analytics service
  • PostMark -- This is a transactional online email service

All of the online services mentioned above are not free. SMTP and Sendmail are free. The above list of supported email drivers is not exhaustive but lists the commonly used drivers.

Laravel Email Configuration

In this section, we will look at how to configure a Laravel application to send emails. But first, we will have to create the project.

Run the following composer command.

composer create-project laravel/laravel email 6.0.*

HERE,

  • The above command will create a new Laravel project using the latest version of Laravel 6.0

The email configuration file is located in the directory /config/mail.php but just like many configurations in Laravel, we set the configuration settings in the .env

Open .env file and locate the following lines

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

HERE,

  • MAIL_DRIVER=smtp - sets the default driver to SMTP protocol
  • MAIL_HOST=smtp.mailtrap.io - uses Mailtrap as the default SMTP server. This is a premium online service but you can sign up for a free account online and work with it in a limited sense. The free mailbox as of this writing is limited to 50 emails only. But this will do for our example.
  • MAIL_PORT=2525 - sets the SMTP port for the SMTP Server
  • MAIL_USERNAME=null - sets the SMTP username. You will have to replace this with the value that you will get from Mailtrap
  • MAIL_PASSWORD=null - sets the SMTP password. You will have to replace this with the value that you get from Mailtrap
  • MAIL_ENCRYPTION=null - sets the encryption methods to be used. TLS, SSL are some of the common encryption methods.

The above are the default email settings in .env but we will need to add 2 more settings that the configuration file deals with.

MAIL_FROM_ADDRESS=
MAIL_FROM_NAME=

HERE,

  • The above are used by Laravel when sending emails to show the from email address and name part of the email that is sent.

The last but not least is the application name and URL. it is usually included in the emails that are sent to subscribers.

APP_NAME=Laravel
APP_URL=http://localhost

 

The complete configuration settings should be as follows

APP_NAME=KodeBlogEmailExample
APP_URL=http://localhost:8000

~

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=
MAIL_FROM_NAME=

 

Laravel Sending Email

Now that we have done the configurations, it's time to send some emails. We will be using Mailables. A Mailable class is a simple class that allows us to configure email parameters and send them. We will create two Mailables in this section, one for plain email and the other for HTML email.

Laravel Email Mailables

Run the following artisan commands

php artisan make:mail HelloMail
php artisan make:mail HTMLMail

HERE,

  • The above commands create two classes HelloMail and HTMLMail in the directory app/Mail.

Update the code to the following

Replace app/Mail/HelloMail.php with the following code

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class HelloMail extends Mailable
{
    use Queueable, SerializesModels;

    public $data;

    public function __construct($data)
    {
        $this->data = $data;
    }

    public function build()
    {
        return $this->from($this->data['from'], $this->data['from_name'])
            ->subject($this->data['subject'])
            ->text('emails.plain');
    }
}

HERE,

  • public $data; defines a public variable data that we will be using to pass in parameters from our controller.
  • public function __construct($data){ $this->data = $data; } we pass in the value of the variable $data and assign it to the class variable $this->data.
  • public function build(){...} in this method, we configure the parameters that we need to send the email. We set the from email, from name, and subject using the values that we passed in from the controller using the $dataparameter.
  • -\>text(\'emails.plain\'); we are calling the text method so that Laravel sends this email as plain text. We are loading a blade view named html located in /resources/views/emails/plain.blade.php

Replace app/Mail/HTMLMail.php with the following code

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class HTMLMail extends Mailable
{
    use Queueable, SerializesModels;

    public $data;

    public function __construct($data)
    {
        $this->data = $data;
    }

    public function build()
    {
        return $this->from($this->data['from'], $this->data['from_name'])
            ->subject($this->data['subject'])
            ->view('emails.html');
    }
}

HERE,

  • The code in the configuration is the same as for the above HelloMail Mailable.
  • ->view('emails.html'); the view method instructs Laravel to send this email in HTML Form. We are loading a blade view named html located in /resources/views/emails/html.blade.php

Laravel Email Views

Let's now create our Email views

Create the following files in the directory /resources/views/emails. If the emails directory does not exist then you can create it manually.

Add the following code to plain.blade.php

{{ $data['name'] }}

Laravel sending email made simple

{{ $data['message'] }}

HERE,

  • {{ $data['name'] }} uses traditional blade template to display the value of the name variable
  • {{ $data\['message'] }} displays the message variable value.

Add the following code to html.blade.php

<h2>{{$data['name']}}</h2>
<p>Laravel sending email made simple</p>
<p>{{$data['message']}}</p>

HERE,

  • The code above displays the same data as the plain email except in this template, we are formatting the data using HTML tags.

Laravel Email Controller

Let's first create a controller that will define the methods that we will use to send emails.

php artisan make:controller EmailController

Open the newly created controller and add the following functions.

<?php

namespace App\Http\Controllers;

use App\Mail\HelloMail;
use App\Mail\HTMLMail;
use Mail;

class EmailController extends Controller
{
    public function plainEmail()
    {
        $data = [
            'name'      => 'Biggus Dickus',
            'message'   => 'The life of brian',
            'subject'   => 'Laravel Plain Email',
            'from'      => 'info@local.com',
            'from_name' => 'Laravel Plain Email',
        ];

        Mail::to('kazemberodrick69@gmail.com', 'Chappie')->send(new HelloMail($data));

        return "Plain Email Sent. Check your inbox.";
    }

    public function htmlEmail()
    {
        $data = [
            'name'      => 'Biggus Dickus',
            'message'   => 'The life of brian',
            'subject'   => 'Laravel Plain Email',
            'from'      => 'info@local.com',
            'from_name' => 'Laravel HTML Email',
        ];

        Mail::to('kazemberodrick69@gmail.com', 'Chappie')->send(new HTMLMail($data));

        return "HTML Email Sent. Check your inbox.";
    }
}

HERE,

  • use App\Mail\HelloMail; imports the HelloMail Mailable
  • use App\Mail\HTMLMail; imports the HTMLMail Mailable
  • use Mail; imports the Mail class.
  • public function plainEmail(){...} defines the function that the route will be calling to send plain emails. The array variable $data defines the$name and $message variables that we are including in our email message. We are also setting the email subject, from email and name. finally we send the email using Mail::to(...) method of the Mail class and pass in our Mailable class HelloMail in the send method. The HelloMail class is initialized with the $data array variable.
  • public function htmlEmail(){...} sends the HTML email. The explanation for the code is the same as the one for the plain email except for the Mailable class used which is HTMLMail.

Let's now create the routes that we will use to send the emails.

Open /routes/web.php

Add the following routes

Route::get('/plain-email',[
    'uses' => 'EmailController@plainEmail',
]);

Route::get('/html-email',[
    'uses' => 'EmailController@htmlEmail',
]);

HERE,

  • In the above code, we define two routes plain-email and html-email that call the plainEmail and htmlEmail methods in the EmailController class respectively.

Let's now take our application for a spin. For this tutorial. I am using Mailtrap.

Load the following URL in your browser

http://localhost:8000/plain-email

You will get the following message in the browser

Plain Email Sent. Check your inbox.

If you open your mailbox, you should be able to get a message like the following.

Laravel plain email

Load the following URL in your browser

http://localhost:8000/html-email

You will get the following message in the browser

HTML Email Sent. Check your inbox.

Laravel HTML Email

Laravel Snowfire Beautiful HTML Email

The above HTML email is kind of cool but these are not the 90s. Modern day uses expect something more appealing to the eyes. Snowfire Beauty Mail is Laravel email template package that makes this super easy.

The following image shows you what we will built in this section.

Snowfire

As you can see from the above email, we can include images and do more fancy styles with Snowfire without writing any CSS. Let's do it.

First we need to install the Package

Run the following command

composer require snowfire/beautymail dev-master

Next we need to configure the Snowfire service provider

Open /config/app.php

Add the following code to the providers list

Snowfire\Beautymail\BeautymailServiceProvider::class,

Save the changes

We can now publish the configuration file that we can use to customize Snowfire

php artisan vendor:publish --provider="Snowfire\Beautymail\BeautymailServiceProvider"

we are good to go, open /routes/web.php and add the following route.

Route::get('/beauty-email',[
    'uses' => 'EmailController@beautyEmail',
]);

Next define the beautyEmail function in /app/Http/Controllers/EmailController.php

    public function beautyEmail()
    {
        $beautymail = app()->make(\Snowfire\Beautymail\Beautymail::class);
        $beautymail->send('emails.beautymail', ['name' => 'Rodrick'], function ($message) {
            $message
                ->from('bar@example.com')
                ->to('foo@example.com', 'John Smith')
                ->subject('Welcome!');
        });

        return "Beauty Email Sent. Check your inbox.";
    }

HERE,

  • $beautymail = app()->make(\Snowfire\Beautymail\Beautymail::class); defines the $beautymail variable that we will use to send the email
  • $beautymail->send(...) sends the email using the emails.beautymail blade template

Let's now define the blade template

Create a new file beautyemail.blade.php in the directory /resources/views/emails

Add the following code

@extends('beautymail::templates.ark')
@section('content')
@include('beautymail::templates.ark.heading', [
        'heading' => "Hello $name!",
        'level' => 'h1'
    ])
@include('beautymail::templates.ark.contentStart')
<h4 class="secondary"><strong>Hello World</strong></h4>
        <p>This is a test</p>
@include('beautymail::templates.ark.contentEnd')
@include('beautymail::templates.ark.heading', [
        'heading' => 'Another headline',
        'level' => 'h2'
    ])
@include('beautymail::templates.ark.contentStart')
<h4 class="secondary"><strong>Hello World again</strong></h4>
        <p>This is another test</p>
@include('beautymail::templates.ark.contentEnd')
@stop

HERE,

  • @extends('beautymail::templates.ark') our template extends the ark template which comes with the Snowfire package.
  • @section('content') defines the content section
  • @include(...) the include directive is used to insert various components such as headers, sections etc. into our email template.

Load the following URL into your browser.

http://localhost:8000/beauty-email

You should be able to see the above image. If you face any challenges, use the comments section below to ask questions.

Summary

In this tutorial, we have learnt how to send emails using Laravel. We looked at the various email drivers that Laravel supports, how you can send plain and HTML emails.

What next?

If you enjoyed this lesson then show us your appreciation by creating a free accounts on our site. As always we appreciate your comments down below.


...