Laravel 9 Sending Email with Mailtrap Example Tutorial

Throughout this step by step tutorial you will understand how to send emails in Laravel with the help of Mailtrap SMTP, equally important we will explain to you how to use Laravel’s builtin mailable markdown class to send emails.

This tutorial clears the concept of:

  • How to configure mailtrap in Laravel?
  • How to send mail using mailtrap in laravel with Mailable class?

Laravel is one of the best not only but also a quintessential PHP framework of all time; it offers innumerable solutions to ward off the tensions from web developers life.

Today, we are looking for the answer about how to send mail in Laravel with the help of Mailable classes.

This is a core feature and was introduced in Laravel 5.3 version; it is used for sending email in Laravel.

You, need to create a mailable class, configure it and you can send the mail quickly.

For sending mail, you can use various services for example:

  • SMTP
  • Mailgun
  • Amazon SES
  • Sendmail

However we are using Mailtrap to send email in laravel.

Install Laravel Application

Using composer command install a laravel application:

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

Adding Mailtrap in ENV

For creating email sending functionality, you need a mailtrap configuration to configure SMTP settings.

Here is how you get the credentials at mailtrap:

  • Create an account using GitHub or Email at mailtrap.io
  • Login to your account
  • Create inbox project
  • Create on the settings icon
  • Go to the SMTP/POP3 tab
  • Select Laravel from the Integrations dropdown
  • Copy the Laravel mailer details

Laravel offers a recklessly profound API over the popular SwiftMailer library. You can set up a mailing configuration by adding these values in the .env configuration file within your application’s root directory:

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= // sender email
MAIL_FROM_NAME="${APP_NAME}"

Create Markdown Mailable

Use the given command to create Markdown Mailable class:

php artisan make:mail WelcomeMail --markdown=Email.welcomeMail

Thereafter, put the code in app/Mail/WelcomeMail.php:

<?php

namespace App\Mail;

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

class WelcomeMail extends Mailable
{
    use Queueable, SerializesModels;
    public $mailInfo;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($mailInfo)
    {
        $this->mailInfo = $mailInfo;
    }

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

Setting Up Controller

In a subsequent step, we will create a controller that will handle the welcome mail sending code.

php artisan make:controller WelcomeController

Afterwards, place below code in app/Http/Controllers/WelcomeController.php:

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\Mail;
use App\Mail\WelcomeMail;


class WelcomeController extends Controller
{
    public function mailSend() {
        $email = 'mail@hotmail.com';
   
        $mailInfo = [
            'title' => 'Welcome New User',
            'url' => 'https://www.remotestack.io'
        ];
  
        Mail::to($email)->send(new WelcomeMail($mailInfo));
   
        return response()->json([
            'message' => 'Mail has sent.'
        ], Response::HTTP_OK);
    }
}

Make Route

To make GET request to send mail, define a new route in routes/web.php:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\WelcomeController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/mail-send', [WelcomeController::class, 'mailSend']);

Organize Mail Blade View

Subsequently, put the blade view code in resources/views/Email/welcomeMail.blade.php to invoke the mail template for inbox email view:

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

Congratulations! Your account has been created.

@component('mail::button', ['url' => $mailInfo['url']])
Cheers!
@endcomponent

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

Start Sending Mail

Use following command to start application:

php artisan serve

You can send the mail with following route.

http://localhost:8000/mail-send

Conclusion

Finally, the laravel sending mail with the help of mailtrap is over i hope this tutorial wil help you clear the concept of sending mail in the laravel application.