Basic Mailtrap set up with Laravel 6

Paul
2 min readNov 28, 2020

--

This article is a quick guide to set up Mailtrap with laravel 6. It will only cover the basic set up, maybe in future posts I will cover more examples.

Create new laravel 6 project:

composer create-project --prefer-dist laravel/laravel mailtrap_laravel6_demo "6.*"

While your project is building, you can sign up for a Mailtrap basic account. At the time of writing the free account can send 500 test emails per month.

When the project has built, select laravel in the ‘Integrations’ dropdown and copy the MAIL_USERNAME and MAIL_PASSWORD settings into your laravel .env file.

Note: the MAIL_DRIVER setting was changed MAIL_MAILER in Laravel 7. In Laravel 6 we should still use MAIL_DRIVER.

In your terminal:

cd mailtrap_laravel6_demo

Now we want to create a mailable class which uses a markdown template:

php artisan make:mail DemoMail --markdown=emails.demomail

This will make a DemoMail file in the app/Mail directory, and a markdown email in resources/views/emails

For demo purposes add a route in web.php for sending the email. Normally this code would be in the controller or elsewhere:

<?php/*
|--------------------------------------------------------------------------
| 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!
|
*/
use App\\Mail\\DemoMail;
use Illuminate\\Support\\Facades\\Mail;
Route::get('/', function () {
return view('welcome');
});
Route::get('/send-mail', function () { Mail::to('someuser@example.com')->send(new DemoMail()); return 'email has been sent!';
});

Change DemoMail.php to look like this:

<?phpnamespace App\\Mail;use Illuminate\\Bus\\Queueable;
use Illuminate\\Mail\\Mailable;
use Illuminate\\Queue\\SerializesModels;
class DemoMail extends Mailable
{
use Queueable, SerializesModels;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct()
{
//
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->from('admin@example.com', 'Admin')
->subject('Confirmation email')
->markdown('emails.demomail');
}
}

And my demomail.blade.php looks like this:

@component('mail::message')    This is an example email@endcomponent

Now when you visit http://localhost:8000/send-mail you should get the ‘email has been sent!’ response, and you can see your test email in your Mailtrap inbox.

Thanks for reading!

--

--

Paul
Paul

Written by Paul

I am a software developer and I like to write about interesting things I come across in my day to day.

No responses yet