Laravel Test Email Functionality with MailTrap on Localhost

Send your Test Emails in your Laravel project with MailTrap…

Geno Tech
4 min readMay 31, 2023
Laravel Test Email Functionality with MailTrap on Localhost

Email sending is a crucial functionality in our websites. When you develop a Laravel project and want to send emails, Testing in the local environment is difficult. With MailTrap, we can easily test those emails before you go to production. Here are the easy steps you need to follow.

Create a MailTrap Account

First, we need to create a MailTrap account to get our free inbox to test the emails. You can easily create a MailTrap account here. https://mailtrap.io/register/signup?ref=header

You can create a new mailbox after you create a new account and log in to the MailTrap. Inside that, you can see the following screen.

Create a MailTrap Account

Here the most important is SMTP Settings. So we will use those settings under Laravel, which I have highlighted here.

Create a new Laravel Project.

composer create-project --prefer-dist laravel/laravel:^7.0 test_email

Create a new Controller.

Here I am creating a new controller to execute the email-sending function.

php artisan make:controller UserController

Inside that Controller, create the index method to send our mail. Here is my implementation.

<?php

namespace App\Http\Controllers;
use App\Mail\UserMail;
use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Mail;

use Illuminate\Http\Request;

class UserController extends Controller
{
/**
* Get the authenticated User.
*
* @return \Illuminate\Http\JsonResponse
*/
public function index()
{
Mail::to('lahiru.ariyasinghe69@gmail.com')->send(new UserMail());

return true;
}

}

Create a new API route.

Inside the api.php file, We define this new route.

use App\Http\Controllers\UserController;

Route::get('/user/mail/send', [UserController::class, 'index']);

Create the UserMail.php File

UserMail.php is for providing the service to send email. I implemented it under a new folder called Mail.

<?php

namespace App\Mail;

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

class UserMail extends Mailable
{
use Queueable, SerializesModels;

protected $isSuccess, $logo;

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

/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->from('lahiru@gmail.com', 'GenoTech')
->subject('Your Registration is Successful!!!')
->view('emails.user_email',['name'=>"Kasun", 'logo' => $this->logo]);
}
}

Add a Logo Image

I added a logo.php image inside the img folder inside the public folder.

logo.png

Create the user_email.blade.php View File.

This is the view of your email(user_email.blade.php). That is placed under resources/view/emails folder.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<style>
body{
height: 750px;
margin: 2px;
padding: 2px;
font-family: Helvetica, Arial, sans-serif;
}

.button-container{
margin:40px 0;
}

#box{
width: 850px;
margin: 0 auto;
height:100%;
}

#header{
height: 200px;
width: 100%;
position: relative;
display: block;
border-bottom: 1px solid #504597;
}

.button{
background-color: #d60e0e;
border: none;
color: white !important;
padding: 10px 25px;
text-align: center;
text-decoration: none;
margin:auto;
font-size: 22px;
cursor: pointer;
border-radius: 10px;
}

#image {
width: 150px;
height: auto;
margin-top: 16px;
}

#rightbar {
width: 100%;
height: 560px;
padding: 0px;
}

.text-div{
font-size: 18px;
margin-bottom: 3px;
}

#footer {
clear: both;
height: 40px;
text-align: center;
background-color: #2d0f80;
margin: 0px;
padding: 0px;
color: white;
}

p, pre
{
font-size: 18px;
line-height: 1.4;
}

.heading{
color: #504597;
font-size: 24px;
}

</style>
</head>
<body>
<div id="box">
<div id="header">
<img id="image" src="{{ $logo }}">
</div>
<div class="spacing"></div>
<div id ="rightbar">
<h1 class="heading"></h1>
<p >Hi {{$name}} ,</p>
<p>Thank you for registered your business with Genotechies.</p>
<p>Please view the inbox for more details or contact Geno Tech admin for further instructions.</p>

<div class="text-div">Thanks,</div>
<div class="text-div">Geno Team.</div>
</div>
</div>
</body>
</html>

Update the .env File.

Now we are going to update the .env file. You must paste the SMTP settings mentioned above in the MailTrap setup step. Add those settings to the .env.

#==== Email ====
MAIL_MAILER=smtp
MAIL_HOST=sandbox.smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=aaa026510b7SS2
MAIL_PASSWORD=9afce1f21b1DFd
MAIL_ENCRYPTION=tls

Update the mail.php File.

The last step is adding the following snippet to the mail.php file under the config folder.

    'stream' => [
'ssl' => [
'allow_self_signed' => true,
'verify_peer' => false,
'verify_peer_name' => false,
],
],

Otherwise, you cannot send mail from outside the local environment. This is not healthy for security. So do not deploy this to your server. Otherwise, if you do not add this snippet, you will get an error like follows.

    "message": "Connection could not be established with host  :stream_socket_client(): unable to connect to ssl://:465 (No connection could be made because the target machine actively refused it.\r\n)",
"exception": "Swift_TransportException",
"file": "C:\\xampp\\htdocs\\laravel\\varnik_api\\varnik_api\\laravel-app\\vendor\\swiftmailer\\swiftmailer\\lib\\classes\\Swift\\Transport\\StreamBuffer.php",
"line": 261,

Check the Results.

We have done all the steps, and now is the time to check the results. I used Postman here to call the API route and check the email-sending function.

So you can see here the API call returns true. It means the function is called successfully. If you check your MailTrap inbox, you have received the email successfully as below.

This is the end of our chapter. You can comment on your problems if you have any.

Happy Coding !!!!
Found this post useful? Kindly tap the 👏 button below! :)

--

--

Geno Tech

Software Development | Data Science | AI — We write rich & meaningful content on development, technology, digital transformation & life lessons.