Sending Emails in Laravel – All You Want to Know

https://mailtrap.io/wp-content/uploads/2021/05/mailtrap_home-2.png

Updated on September 10, 2021

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, Mailtrap Email Delivery, 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.

It’s really easy to integrate Laravel with Mailtrap. Sign up for a free account to see how.

Sending an 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.

Laravel 7.0 introduces multiple drivers. It means that you can set one of the drivers as a default one in your mail configuration file (Mailgun, for example), but configure sending particular types of messages (let’s say, notifications) with SparkPost.

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

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 SMTP server is one of the recommended SMTP methods 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_MAILER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=465
MAIL_USERNAME=youremail@gmail.com
MAIL_PASSWORD=your password
MAIL_ENCRYPTION=ssl

And if you’re using Mailtrap Email Delivery as your sending solution, we provide the SMTP configuration for you. Just copy-paste the configuration listed in the app, verify your domain, and you’re good to go.

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. 

For July 2020, Laravel 7.0 is the latest released version. 

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

Version Release Bug Fixes Until Security Fixes Until
5.5 (LTS) August 30th, 2017 August 30th, 2019 August 30th, 2020
5.6 February 7th, 2018 August 7th, 2018 February 7th, 2019
5.7 September 4th, 2018 March 4th, 2019 September 4th, 2019
5.8 February 26th, 2019 August 26th, 2019 February 26th, 2020
6 (LTS) September 3rd, 2019 September 3rd, 2021 September 3rd, 2022
7 March 3rd, 2020 September 3rd, 2020 March 3rd, 2021

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 6 and 7 versions, which affect email sending options.

Laravel 6 (LTS) introduced semantic versioning, compatibility with Laravel Vapor, enhanced authorization responses, job middleware, lazy collections, and subquery improvements, as well as other bug fixes and usability improvements.

Laravel 7 delivered Laravel Sanctum (an authentication system), Blade component tags, a developer-focused HTTP client, first-party CORS support, multiple mail drivers, a new artisan test command, along with other bug fixes and usability improvements.

How to send email in Laravel 7.0 using SMTP

To sum up, let’s review an example of coding a message in Laravel 7.0 and testing it with 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 7.0.* in your composer.json file, as recommended in the official guide.

Let’s start by 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.

Try Mailtrap for Free

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_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=1a2b3c4d5e6f7g //your username
MAIL_PASSWORD=1a2b3c4d5e6f7g // your password
MAIL_FROM_ADDRESS=from@example.com
MAIL_FROM_NAME=Example

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' => '/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 ****,  
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!';

});

Run your application. Usually, it should be php artisan serve in development, then go to /send-mail path of your application in the browser (http://127.0.0.1:8000/send-mail when running with php artisan serve.) 

Note that starting from the 5.8 version, Laravel is capable of serving multiple applications. Earlier, only port 8000 was available but now serves scans for free options up to 8009

That’s it. Your application will send a message and you will see it in your Mailtrap inbox:

Capture emails like this in a safe testing environment with Mailtrap.

Verify if the result matches your expectations: whether 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.

Laravel News Links