Sending Emails in Laravel – All You Want to Know

Many Mailtrap users create their apps with PHP and the vast majority of them choose Laravel. It is simple and in addition, is covered in-depth by documentation and tutorials. However, we still observe numerous questions on sending emails with Laravel, testing them, as well as Mailtrap configurations. We have analyzed the most popular requests on Stack Overflow, Reddit as well as Google search and in this post we will provide you with the list of answers. How to send an email with Laravel? How to send a Laravel email via Mailtrap? Why isn’t Laravel mail working? Let’s figure it out.  

Why Laravel and how it works

Laravel is a PHP framework that stands out for its simplicity, modernity, and connectivity. Probably, those characteristics make it especially popular among startups.

Laravel is widely used for building websites, marketplaces, web apps, and even frameworks.

The mail function is essential for these tasks, to register or notify the users, so it’s native in Laravel and provides a wide range of capabilities:

  • A list of integrations for sending emails through local or cloud-based services.  Now Laravel proposes using drivers for SMTP, Mailgun, SparkPost, Amazon SES, and sendmail.
  • Options for queueing emails.
  • Markdown support, which is available in a quite few frameworks. It lets you create beautiful templates and easily include buttons, tables, or panels.
  • Regular plain text and HTML messages.
  • Attaching files of different formats and MIME types, as well as raw data, inline attachments, and even embedding raw data into mail templates.
  • Templating system, which lets you use various templates and configure the view.
  • Message previews in-browser.

In addition, there are some noteworthy options:

  • Localization methods, so that you can set the desired language for a specific user.
  • Local development mailing. This is how you can prevent sending test emails to real inboxes. Mailtrap is one of the preferred options.

What you need to know about Laravel Mail

You will intuitively find all guidelines on the Laravel website and the educational Laracasts portal. That is why we rejected the idea of creating our own tutorial. For a better understanding, we decided to outline some basic principles, provide you with examples of creating an email in Laravel, and give you some tips and explanations.

Building email in Laravel

Here are a couple of basic things to keep in mind.

  • Laravel includes its own command-line interface called Artisan. (Yes, it definitely refers to their slogan “The PHP framework for web artisans”). It provides a bundle of useful commands, for email creation in particular. To get all available commands, type:
php artisan list 
  • Each email category can be represented as a “mailable”. It’s a class that is responsible for building a specific email message using a set of methods.

For example:

php artisan make:mail NewUserNotification

command generates a class, which you’ll find at ‘app/Mail/NewUserNotification.php. The build() method of this class creates email messages:

public function build()
{
    return $this->from('example@example.com')
        ->view('emails.newuser');
}

This way, we have written a mailable with a build() method. Of course, it’s a minimal example, but you can make the necessary configuration and the next time you need to send it again, you will just type:

Mail::to($emailAddress)->send(new NewUserNotification);

Note: Mailables were introduced in Laravel 5.3.

Sending email in Laravel

To send an email, you have a bunch of options. Laravel’s creators recommend using one of the API based drivers: Mailgun, SparkPost, or Amazon SES. For configurations, follow this section of the Laravel Documentation.

You are also free to use any SMTP server you prefer, like Gmail. The related configurations are made in the config/mail.php file. In the default Laravel setup, the email configuration is read from environment variables so to edit them, you should save your changes to the .env file (you will find it in the root directory).

The Mailtrap fake SMTP server is a default SMTP method in Laravel. It helps you avoid sending test emails to real inboxes by accident. It is designed to catch these interim emails and help you debug them. With Mailtrap, your email will never land in the real inbox in any of the email clients.

So, if you are ready to send your message to your own or even your customer’s inbox, don’t forget to replace the configuration with that of the real server. For example:

MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=465
MAIL_USERNAME=youremail@gmail.com
MAIL_PASSWORD=your password
MAIL_ENCRYPTION=ssl

Laravel versions

A new version of Laravel is released every six months. Then bug fixes are provided for another six months while security fixes are delivered within a year. Also, starting from 5.1, Laravel offers long-term support (LTS) version, with bug fixes valid for two years and security fixes – for three.

We recommend sticking to the latest available version or to the latest long-term one. This way, you will get a stable result while taking advantage of all helpful additions and changes.

For March 2019, Laravel 5.8 is the latest released version.

We observe that in 2018 users were still working with Laravel 5.6, 5.4, 5.3, or even 5.2 versions. But versions below 5.5 (LTS) were no longer supported:

VersionReleaseBug Fixes UntilSecurity Fixes Until
5.0February 4th, 2015August 4th, 2015February 4th, 2016
5.1 (LTS)June 9th, 2015June 9th, 2017June 9th, 2018
5.2December 21st, 2015June 21st, 2016December 21st, 2016
5.3August 23rd, 2016February 23rd, 2017August 23rd, 2017
5.4January 24th, 2017July 24th, 2017January 24th, 2018
5.5 (LTS)August 30th, 2017August 30th, 2019August 30th, 2020
5.6February 7th, 2018August 7th, 2018February 7th, 2019
5.7September 4th, 2018March 4th, 2019September 4th, 2019
5.8February 26th, 2019August 26th, 2019February 26th, 2020

Source: https://laravel.com/docs/master/releases

Sometimes, the use of the old versions might result in some performance issues. Most likely, you might just miss some functionality and waste your time. Here is a list of some important updates delivered in 5.x versions, which affect email sending options.

Laravel 5.3 delivered a bunch of updates and among them introduced mailables. It significantly streamlines sending numerous typical notifications.

Laravel 5.4 added Markdown support for emails eliminating a need to create complex HTML attributes. Not many frameworks can claim this feature.

Laravel 5.5 is the latest available LTS version. For the email functionality, it brought renderable mailables. It means that now you can preview your emails in a browser before sending.

Laravel 5.6 introduced major user experience improvements and updated underlying Symfony components.

Laravel 5.7 along with functionality improvements, added email localization options so that you can set the preferred language for your notifications.

Laravel 5.8 adds support for the latest versions of related frameworks and improves our email sending experience with advanced email validation and enhanced artisan serve command. It lets you run several applications simultaneously.

How to send email in Laravel 5.8 using SMTP

To sum up, let’s review an example of coding a message in Laravel 5.8 and testing it with the Mailtrap’s fake SMTP service. We will take advantage of Laravel’s awesome features like Blade templates, Mailable class, and Markdown support.

We assume that you have been already using Laravel for building your application. If you were working in one of the previous versions, update your laravel/framework dependency to 5.8.* in your composer.json file, as recommended in the official guide.

Let’s start with defining an SMTP server and setting the mailing configuration. We prefer to test our notifications with Mailtrap first, to make sure our code works fine and the content of the messages is rendered properly. Mailtrap is a default server in Laravel, so you need just to type in your credentials. You will find them in the SMTP Settings tab of your Inbox. Also, you can use Integrations data from the same tab. Choose Laravel from the list, copy the following details and paste them to your .env file:

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=1a2b3c4d5e6f7g //your username generated by Mailtrap
MAIL_PASSWORD=1a2b3c4d5e6f7g // your password generated by Mailtrap
MAIL_FROM_ADDRESS=from@example.com
MAIL_FROM_NAME=Example

In most cases, the .env file configuration is enough. But alternatively, you can set your config/mail.php file to the following content (it is also available in the list of integrations in Mailtrap):

<?php
return [
  "driver" => "smtp",
  "host" => "smtp.mailtrap.io",
  "port" => 2525,
  "from" => array(
      "address" => "from@example.com",
      "name" => "Example"
  ),
  "username" => "1a2b3c4d5e6f7g" // your username,
  "password" => "1a2b3c4d5e6f7g" // your password,
  "sendmail" => "/usr/sbin/sendmail -bs"
];

Now let’s move to the CLI:

php artisan make:mail MailtrapExample

This way, we have created a Mailable class, with the name “MailtrapExample.php”. Now we should find it in the Mail directory in app/Mail. We have a template, which contains basic needed functions so that we should just modify it.

<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class MailtrapExample extends Mailable
{
    use Queueable, SerializesModels;
    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }
    /**
     * Build the message.
     *
     * @return $this
     */
public function build()
    {
        return $this->from('mail@example.com', 'Mailtrap')
            ->subject('Mailtrap Confirmation')
            ->markdown('mails.exmpl')
            ->with([
                'name' => 'New Mailtrap User',
                'link' => 'https://mailtrap.io/inboxes'
            ]);
    }

We’ve added a sender, a subject, a couple of variables and introduced the Markdown support.

Now it’s time to create the body of our message. For this purpose, we will use a Blade template. We have specified that our mailable is located in the mails.exmpl. Now we need to create a ‘mails’ directory with a blade template file ‘exmpl.blade.php’. inside. Templates represent views in Laravel, so keep the template file in the resources/views/mails directory.

@component('mail::message')
Hello **{{$name}}**,  {{-- use double space for line break --}}
Thank you for choosing Mailtrap!

Click below to start working right now
@component('mail::button', ['url' => $link])
Go to your inbox
@endcomponent
Sincerely,  
Mailtrap team.
@endcomponent

Our simple configuration is done, and we can move forward with sending our message. Specify the route in the routes/web.php:

<?php

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

Route::get('/send-mail', function () {

    Mail::to('newuser@example.com')->send(new MailtrapExample()); 

    return 'A message has been sent to Mailtrap!';

});

Output:

email-build--in-laravel-test-mailtrap

Verify if the result matches your expectations: if all elements are displayed correctly and links work properly. View the Check HTML and Analysis tabs in Mailtrap to make sure your messages won’t be considered spam and will be rendered correctly in most email clients.

Once you are satisfied with the results of tests, replace SMTP configurations with your production server or configure any other option to send emails to real inboxes.