How to Send Email in Laravel 7 with Mailable and Mailtrap

Last updated on by Digamber
In this Laravel 7/6 tutorial, we will learn how to send emails from the Laravel application using the Mailtrap SMTP server. Generically, we will comprehend the working process of markdown mailable class and simultaneously work with every aspect required to send email securely, faster, and efficiently.

Send Simple Email in Laravel 7 with Mailable

Email sent from the Laravel application represent a mailable class; every mailable class is kept inside the app/Mail folder.

The php artisan make:mail your_class_name command forms the Mailable class, this also creates the blade view email template, which manages the mailer view.

What is Mailtrap?

Mailtrap is a traditional tool, and generically it is utilized as a fake SMPT (Simple Mail Transfer Protocol) server. Web developers and software development teams use it to send, test, view, and share emails, possibly sent from a staging environment without assimilating the spamming.

Workflow to Send an Email in Laravel

Sending mail from Laravel from the localhost environment can be assimilated by developers by the following process.

  1. Build a Laravel project.
  2. Create a Mailtrap account to handle requests from the local environment.
  3. Unite the Mailtrap details in the .env file.
  4. Formulate a Mailable class in Laravel.
  5. Generate Mail controller, write down the logic to send email
  6. Create a route, bind the mail controller to it.
  7. Create a mailer template in the view.
  8. Start your development server and send test emails.

Create Laravel Project

Install brand new Laravel project by executing the below-mentioned command.

composer create-project laravel/laravel --prefer-dist laravel-send-email

Move inside the newly created project directory.

cd laravel-send-email

Setting Up Mailtrap Mail Configuration

First, you need to create the Mailtrap account. This app tests the emails sending from the development environment, It restrains the spam and makes you test mails smoothly sending from laravel app.

Go to mailtrap dashboard, click on the small gear icon. Copy the username and password from SMTP Settings tab.

After creating the account, open .env file and incorporate the mailtrap configuration.

MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME= // mailtrap username
MAIL_PASSWORD= // mailtrap password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS= // email from address

Add the respective details for using Gmail or custom email address.

Generate Laravel Mailable Markdown Class

Theoretically, the mailable class in Laravel used for creating emails. It collects the data and passes the data to the view. Initializing the mailing API is unquestionably simple and straightforward.

Run the artisan command to create a new mailable:

 php artisan make:mail EmailDemo --markdown=Email.demoEmail

Above artisan command generates app/Mail/EmailDemo.php file. We will pass on the data to the view that we need to send though the email.

<?php

namespace App\Mail;

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

class EmailDemo extends Mailable
{
    use Queueable, SerializesModels;
    public $mailData;


    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->markdown('Email.demoEmail')
              ->with('mailData', $this->mailData);
    }
}

The Email.demoEmail template was generated by the mailable command, and the mailData variable will carry the data that we will define in the coming step.

Create Controller to Send and Email

Run the following command to generate a new new controller, essentially we will define the have the logic to display the user’s list. Run the command to create the controller.

php artisan make:controller MailController

Open app/Http/Controllers/MailController.php and place the following code.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

use Illuminate\Support\Facades\Mail;
use App\Mail\EmailDemo;
use Symfony\Component\HttpFoundation\Response;


class MailController extends Controller {
    
    public function sendEmail() {
        $email = 'positronx@gmail.com';
   
        $mailData = [
            'title' => 'Demo Email',
            'url' => 'https://www.positronx.io'
        ];
  
        Mail::to($email)->send(new EmailDemo($mailData));
   
        return response()->json([
            'message' => 'Email has been sent.'
        ], Response::HTTP_OK);
    }

}

Import EmailDemo Mailable class along with that also import Mail Facade and Http Response service. Primarily, we noted down the central logic that allows us to send the email from the Laravel app.

A proper response should be shown to the user after successfully sending the email, this is being handled through HttpFoundation/Response API.

Create Route to Send Mail

This step guides you through creating a route and making the consensus between the mail controller and the sendEmail function. Open routes/web.php file and incorporate the given below code.

Route::get('/send-email', 'MailController@sendEmail');

Create Email Template

Now, we have configured almost every required element. The time has come to set up the view for an email template that we will send on the emails. Remember, we created the mailable class; it has also created the email view.

So, go to resources/web.php/Email/demoEmail.blade.php and place the following code.

@component('mail::message')
# {{ $mailData['title'] }}

The body of your message.

@component('mail::button', ['url' => $mailData['url']])
Button Text
@endcomponent

Thanks,<br>
{{ config('app.name') }}
@endcomponent

Send Email in Laravel

Run the below-mentioned command to send the mail on mailtrap via Laravel.

php artisan serve

You can send the mail with following route.

http://localhost:8000/send-email