Send mail using mailtrap in laravel

There are plenty of ways or services to send E-mail in the Laravel application. 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 like integration for sending mail through multiple drivers like SMTP, Mailgun, Amazon SES.

In addition, it provides options for queueing mails, markdown support as well as plain text or HTML messages.

What is Mailtrap and Why to Use it?

Mailtrap is a test mail server solution that allows testing email notifications without sending them to the real users of your application.

Mailtrap is a service for the safe testing of emails sent from the development and staging environments. Mailtrap catches your emails in a virtual inbox so that you can test and optimize your email campaigns before sending them to real users.

For your better understanding, we have divided our application into some parts :

  • Step 1: Create New Application
  • Step 2: Database Configuration
  • Step 3: Mail Configuration
  • Step 4: Create Mail
  • Step 5: Create Blade View
  • Step 6: Add Route
  • Step 7: Running Application

Note: If you already have a Laravel application then you can skip the first and second steps.

Mailtrap Account

First, you need to create an account on Mailtrap if you don't have one. You can use this link Mailtrap

After creating an account you will get mail credentials which you can use for testing.

Create New Application

First, open the terminal and create a new Laravel application using the below command :

composer create-project --prefer-dist laravel/laravel MailtrapExample
//If you already installed laravel globel installer
laravel new MailtrapExample

Database Configuration

Let's configure a database for our application. If you don't have a database then create a new one. After creating the database open .env file from the root directory of your project. if .env file is missing from the project then copy content from .env.example and create file. .env file defines many common environment variables.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=**********
DB_USERNAME=*********
DB_PASSWORD=*********

Mail Configuration

First of all let's configure our mail, for that you have to configure mail driver, mail host, mail port, Mailtrap credentials like below example:

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=test@mailtrap.com
MAIL_FROM_NAME="${APP_NAME}"

Create Mail Class

In Laravel, each type of mail your application sends is called a Mailable class. All Mailable classes are stored in app/Mail directory in your project. Don't worry if it is not in your application, it's automatically created while creating a mailable class.

So let's create a mailable class that will handle sending mail to users. For that enter the below command into your terminal :

php artisan make:mail WelcomeMail

This command will create app/Mail/WelcomeMail.php and resources/views/mail/welcome-mail.blade.php files. The mailable class will handle the logic for mail while the view will send through mail to the user. Here you can also send plain text.

<?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 function __construct()
    {
        //
    }

    public function build()
    {
        return $this->from(env('MAIL_FROM_ADDRESS'), 'Mailtrap')
            ->subject('Welcome To Codewolfy')
            ->markdown('mail.welcome-mail') //View to send
            ->with([
                'name' => 'Groot',
            ]);
    }
}

Here, in the build method, you can define parameters for mail like from method handle, from address, subject, view, and custom parameters used in the view. In this example we have passed static values, you can use dynamic values for each parameter using __construct() like the subject or from address.

Create Blade View

The resources\views\mail\welcome-mail.blade.php has already been created with the Mailable class. Let's make some changes to the view.

@component('mail::message')
# Welcome {{$name}}
This mail is sent using Mailtrap.
Thanks,
{{ config('app.name') }}
@endcomponent

Create Route

The last thing we need to add is to create a route that will send mail to the user. Here we will create send-mail route and also pass the email address as a route parameter so you can test it with different mail addresses. For this example, we are not creating a controller to handle this route.

routes\web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Mail\WelcomeMail;
use Illuminate\Support\Facades\Mail;

Route::get('/', function () {
    return view('welcome');
});
Route::get('/send-mail/{email}', function ($email) {

    Mail::to($email)->send(new WelcomeMail());

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

});

In the above, we have defined route which gets user entered email and send mail using a mailable class and display message. You can use try and catch for error handling.

Running Application

php artisan serve

open below URL into your browser :

http://127.0.0.1:8000/send-mail/test@test.com

After the success message visit your Mailtrap inbox and it will show new mail. You can change the mail address into the URL as per your requirement or use it from a database.