Test mail functionality in laravel using mailtrap

There are plenty of ways or services to send E-mail in 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 option 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 has Laravel application then you can skip first and second step.

Mailtrap Account

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

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

Create New Application

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

Database Configuration

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

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

Let's head back to terminal at root directory of project and enter below command :

.env

    
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 sent by your application is referred as Mailable class. All Mailable classes are stored at app/Mail directory into your project. Don't worry if it is not in your application, it's automatically created while creating mailable class.

So let's create mailable class which will handle sending mail to user. For that enter 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. Mailable class will handle logic for mail while view will send through mail to user. Here you can also send plain text.

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 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, into build method you can define parameter for mail like from method handle, from address, subject, view and custom parameters used in view. In this example we have passed static values, you can use dynamic values for each parameter using __construct() like subject or from address.

Create Blade View

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

resources\views\mail\welcome-mail.blade.php

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

Create Route

Last thing we need to add is create route which will send mail to user. Here we will create send-mail route and also pass email address as route parameter so you can test it with different mail addresses. For this example, we are not creating 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 above, we have defined route which get user entered mail and send mail using 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 success message visit your Mailtrap inbox and it will show new mail. You can change mail address into URL as per your requirement or use it from database.


Share your thoughts

Ask anything about this examples