Laravel Mail Preview is an amazing package that can display a small overlay whenever a mail is sent. The overlay contains a link to the mail that was just sent. This can be handy when testing out emails in a local environment.
Installation & Setup
You can install the package via composer:
composer require spatie/laravel-mail-preview
Configuring the mail transport
This package contains a mail transport called preview. We recommend only using this transport in non-production environments. To use the preview transport, change the mailers.smtp.transport to preview in your config/mail.php file:
// in config/mail.php
'mailers' => [
'smtp' => [
'transport' => 'preview',
// ...
],
// ...
],
Registering the Preview Middleware Route
The package can display a link to sent emails whenever they are sent. To use this feature, you must add the Spatie\MailPreview\Http\Middleware\AddMailPreviewOverlayToResponse middleware to the web middleware group in your kernel.
// in app/Http/Kernel.php
protected $middlewareGroups = [
'web' => [
// other middleware
\Spatie\MailPreview\Http\Middleware\AddMailPreviewOverlayToResponse::class,
],
// ...
];
You must also add the mailPreview to your routes file. Typically, the routes file will be located at routes/web.php.
// in routes/web.php
Route::mailPreview();
This will register a route to display sent mails at /spatie-mail-preview. To customize the URL, pass the URL you want to the macro.
Route::mailPreview('custom-url-where-sent-mails-will-be-shown');
Publishing the config file
Optionally, you can publish the config file with:
php artisan vendor:publish --provider="Spatie\MailPreview\MailPreviewServiceProvider" --tag="mail-preview-config"
Publishing the views
Optionally, you can publish the views that render the preview overlay and the mail itself.
php artisan vendor:publish --provider="Spatie\MailPreview\MailPreviewServiceProvider" --tag="mail-preview-views"
Usage
Every time an email is sent, an .html and .eml file will be saved in the directory specified in the storage_path of the mail-preview config file. The name includes the first recipient and the subject:
1457904864_john_at_example_com_invoice_000234.html
1457904864_john_at_example_com_invoice_000234.eml
You can open the .html file in a web browser. The .eml file in your default email client to have a realistic look at the final output.
Preview in a web browser
When you open the .html file in a web browser you’ll be able to see how your email will look.
At the beginning of the generated file you’ll find an HTML comment with all the message info:
<!--
From:{"info@acme.com":"Acme HQ"},
to:{"jack@gmail.com":"Jack Black"},
reply-to:{"info@acme.com"},
cc:[{"finance@acme.com":"Acme Finance"}, {"management@acme.com":"Acme Management"}],
bcc:null,
subject:Invoice #000234
-->
This package has a lot of options and many more, If you want to learn more, you can visit its documentation at Github.