• Stars
    star
    1,134
  • Rank 39,431 (Top 0.9 %)
  • Language
    PHP
  • License
    MIT License
  • Created about 8 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A mail driver to quickly preview mail

A mail driver to quickly preview mail

Latest Version on Packagist GitHub Workflow Status Software License Total Downloads

This package can display a small overlay whenever a mail is sent. The overlay contains a link to the mail that was just sent.

screenshot

This can be handy when testing out emails in a local environment.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

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 to only use 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 mails 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"

This is the content of the config file that will be published at config/mail-preview.php:

return [
    /*
     * By default, the overlay will only be shown and mail will only be stored
     * when the application is in debug mode.
     */
    'enabled' => env('APP_DEBUG', false),

    /*
     * All mails will be stored in the given directory.
     */
    'storage_path' => storage_path('email-previews'),

    /*
     * This option determines how long generated preview files will be kept.
     */
    'maximum_lifetime_in_seconds' => 60,

    /*
     * When enabled, a link to mail will be added to the response
     * every time a mail is sent.
     */
    'show_link_to_preview' => true,

    /*
     * Determines how long the preview pop up should remain visible.
     *
     * Set this to `false` if the popup should stay visible.
     */
    'popup_timeout_in_seconds' => 8,
];

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"

You can modify the views that will be published at resources/views/vendor/mail-preview to your liking.

Usage

Everytime 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 of 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:{"[email protected]":"Acme HQ"},
to:{"[email protected]":"Jack Black"},
reply-to:{"[email protected]"},
cc:[{"[email protected]":"Acme Finance"}, {"[email protected]":"Acme Management"}],
bcc:null,
subject:Invoice #000234
-->

Events

Whenever a mail is stored on disk, the Spatie\MailPreview\Events\MailStoredEvent will be fired. It has three public properties:

  • message: an instance of Swift_Mime_SimpleMessage
  • pathToHtmlVersion: the path to the html version of the sent mail
  • pathToEmlVersion: the path to the email version of the sent mail

Making assertions against sent mails

Currently, using Laravel's Mail::fake you cannot make any assertions against the content of a mail, as the using the fake will not render the mail.

The SentMails facade provided this package does allow you to make asserts against the content.

This allows you to make assertions on the content of a mail, without having the mailable in scope.

// in a test

Artisan::call(CommandThatSendsMail::class);

Spatie\MailPreview\Facades\SentMails::assertLastContains('something in your mail');

Let's explain other available assertions method using this mailable as example.

namespace App\Mail;

use Illuminate\Mail\Mailable;

class MyNewSongMailable extends Mailable
{
    public function build()
    {
        $this
            ->to('[email protected]')
            ->cc('[email protected]')
            ->bcc('[email protected]')
            ->subject('Here comes the sun')
            ->html("It's been a long cold lonely winter");
    }
}

In your code you can send that mailable with:

Mail::send(new MyNewSongMailable());

In your tests you can assert that the mail was sent using the assertSent function. You should pass a callable to assertSent which will get an instance of SentMail to it. Each sent mail will be passed to the callable. If the callable returns true the assertions passes.

use Spatie\MailPreview\Facades\SentMails;
use \Spatie\MailPreview\SentMails\SentMail;

SentMails::assertSent(fn (SentMail $mail) => $mail->bodyContains('winter')); // will pass
SentMails::assertSent(fn (SentMail $mail) => $mail->bodyContains('spring')); // will not pass

You can use as many assertion methods on the SentMail as you like.

SentMails::assertSent(function (SentMail $mail)  {
    return
        $mail->subjectContains('sun') &&
        $mail->hasTo('[email protected]')
        $mail->bodyContains('winter');

The Spatie\MailPreview\Facades\SentMails has the following assertions methods:

  • assertCount(int $expectedCount): assert how many mails were sent
  • assertLastContains(string $expectedSubstring): assert that the body of the last sent mail contains a given substring
  • assertSent($findMailCallable, int $expectedCount = 1): explained above
  • assertTimesSent(int $expectedCount, Closure $findMail)
  • assertNotSent(Closure $findMail)

Additionally, the Spatie\MailPreview\Facades\SentMails has these methods:

  • all: returns an array of sent mails. Each item will be an instance of sentMail
  • count(): returns the amount of mails sent
  • last: returns an instance of SentMail for the last sent mail. If no mail was sent null will be returned.
  • lastContains: returns true if the body of the last sent mail contains the given substring
  • timesSent($findMailCallable): returns the amount of mails the were sent and that passed the given callable

The sentMail class provides these assertions:

  • assertSubjectContains($expectedSubstring)
  • assertFrom($expectedAddress)
  • assertTo$expectedAddress)
  • assertCc($expectedAddress)
  • assertBcc($expectedAddress)
  • assertContains($substring): will pass if the body of the mail contains the substring

Additionally, sentMail contains these methods:

  • subject(): return the body of a mail
  • to(): returns all to recipients as an array
  • cc(): returns all cc recipients as an array
  • bcc(): returns all bcc recipients as an array
  • body(): returns the body of a mail
  • subjectContains): returns a boolean
  • hasFrom($expectedAddress): return a boolean
  • hasTo($expectedAddress): return a boolean
  • hasCc($expectedAddress): return a boolean
  • hasBcc($expectedAddress): return a boolean

Changelog

Please see CHANGELOG for more information on what has changed recently.

UPGRADING

Please see UPGRADING for what to do to switch over from themsaid/laravel-mail-preview, and how to upgrade to newer major versions.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

The initial version of this package was created by Mohamed Said, who graciously entrusted this package to us at Spatie.

License

The MIT License (MIT). Please see License File for more information.

More Repositories

1

laravel-permission

Associate users with roles and permissions
PHP
11,600
star
2

laravel-medialibrary

Associate files with Eloquent models
PHP
5,427
star
3

laravel-backup

A package to backup your Laravel app
PHP
5,337
star
4

laravel-activitylog

Log activity inside your Laravel app
PHP
5,128
star
5

browsershot

Convert HTML to an image, PDF or string
PHP
4,434
star
6

laravel-query-builder

Easily build Eloquent queries from API requests
PHP
3,675
star
7

laravel-analytics

A Laravel package to retrieve pageviews and other data from Google Analytics
PHP
2,948
star
8

image-optimizer

Easily optimize images using PHP
PHP
2,450
star
9

async

Easily run code asynchronously
PHP
2,401
star
10

crawler

An easy to use, powerful crawler implemented in PHP. Can execute Javascript.
PHP
2,400
star
11

laravel-responsecache

Speed up a Laravel app by caching the entire response
PHP
2,248
star
12

data-transfer-object

Data transfer objects with batteries included
PHP
2,220
star
13

laravel-translatable

Making Eloquent models translatable
PHP
2,030
star
14

laravel-sitemap

Create and generate sitemaps with ease
PHP
2,011
star
15

dashboard.spatie.be

The source code of dashboard.spatie.be
PHP
1,940
star
16

laravel-fractal

An easy to use Fractal wrapper built for Laravel and Lumen applications
PHP
1,845
star
17

package-skeleton-laravel

A skeleton repository for Spatie's Laravel Packages
PHP
1,714
star
18

laravel-collection-macros

A set of useful Laravel collection macros
PHP
1,602
star
19

laravel-newsletter

Manage Mailcoach and MailChimp newsletters in Laravel
PHP
1,570
star
20

period

Complex period comparisons
PHP
1,515
star
21

checklist-going-live

The checklist that is used when a project is going live
1,489
star
22

laravel-tags

Add tags and taggable behaviour to your Laravel app
PHP
1,454
star
23

opening-hours

Query and format a set of opening hours
PHP
1,340
star
24

schema-org

A fluent builder Schema.org types and ld+json generator
PHP
1,284
star
25

eloquent-sortable

Sortable behaviour for Eloquent models
PHP
1,268
star
26

laravel-cookie-consent

Make your Laravel app comply with the crazy EU cookie law
PHP
1,268
star
27

laravel-sluggable

An opinionated package to create slugs for Eloquent models
PHP
1,236
star
28

laravel-searchable

Pragmatically search through models and other sources
PHP
1,217
star
29

pdf-to-image

Convert a pdf to an image
PHP
1,207
star
30

once

A magic memoization function
PHP
1,159
star
31

laravel-honeypot

Preventing spam submitted through forms
PHP
1,134
star
32

laravel-image-optimizer

Optimize images in your Laravel app
PHP
1,121
star
33

laravel-google-calendar

Manage events on a Google Calendar
PHP
1,119
star
34

laravel-settings

Store strongly typed application settings
PHP
1,100
star
35

regex

A sane interface for php's built in preg_* functions
PHP
1,097
star
36

laravel-data

Powerful data objects for Laravel
PHP
1,073
star
37

image

Manipulate images with an expressive API
PHP
1,064
star
38

array-to-xml

A simple class to convert an array to xml
PHP
1,056
star
39

laravel-multitenancy

Make your Laravel app usable by multiple tenants
PHP
1,020
star
40

laravel-uptime-monitor

A powerful and easy to configure uptime and ssl monitor
PHP
997
star
41

db-dumper

Dump the contents of a database
PHP
987
star
42

laravel-model-states

State support for models
PHP
968
star
43

laravel-view-models

View models in Laravel
PHP
963
star
44

simple-excel

Read and write simple Excel and CSV files
PHP
930
star
45

laravel-web-tinker

Tinker in your browser
JavaScript
925
star
46

laravel-webhook-client

Receive webhooks in Laravel apps
PHP
908
star
47

laravel-db-snapshots

Quickly dump and load databases
PHP
889
star
48

laravel-mix-purgecss

Zero-config Purgecss for Laravel Mix
JavaScript
887
star
49

laravel-schemaless-attributes

Add schemaless attributes to Eloquent models
PHP
880
star
50

blender

The Laravel template used for our CMS like projects
PHP
879
star
51

calendar-links

Generate add to calendar links for Google, iCal and other calendar systems
PHP
877
star
52

laravel-webhook-server

Send webhooks from Laravel apps
PHP
870
star
53

laravel-menu

Html menu generator for Laravel
PHP
854
star
54

phpunit-watcher

A tool to automatically rerun PHPUnit tests when source code changes
PHP
831
star
55

laravel-failed-job-monitor

Get notified when a queued job fails
PHP
826
star
56

laravel-model-status

Easily add statuses to your models
PHP
818
star
57

laravel-schedule-monitor

Monitor scheduled tasks in a Laravel app
PHP
800
star
58

form-backend-validation

An easy way to validate forms using back end logic
JavaScript
800
star
59

temporary-directory

A simple class to work with a temporary directory
PHP
796
star
60

laravel-feed

Easily generate RSS feeds
PHP
789
star
61

laravel-server-monitor

Don't let your servers just melt down
PHP
769
star
62

fork

A lightweight solution for running code concurrently in PHP
PHP
751
star
63

enum

Strongly typed enums in PHP supporting autocompletion and refactoring
PHP
737
star
64

laravel-tail

An artisan command to tail your application logs
PHP
726
star
65

valuestore

Easily store some values
PHP
722
star
66

laravel-package-tools

Tools for creating Laravel packages
PHP
722
star
67

laravel-event-sourcing

The easiest way to get started with event sourcing in Laravel
PHP
716
star
68

geocoder

Geocode addresses to coordinates
PHP
709
star
69

pdf-to-text

Extract text from a pdf
PHP
707
star
70

ssh

A lightweight package to execute commands over an SSH connection
PHP
696
star
71

menu

Html menu generator
PHP
688
star
72

laravel-url-signer

Create and validate signed URLs with a limited lifetime
PHP
685
star
73

ssl-certificate

A class to validate SSL certificates
PHP
675
star
74

laravel-route-attributes

Use PHP 8 attributes to register routes in a Laravel app
PHP
674
star
75

laravel-validation-rules

A set of useful Laravel validation rules
PHP
663
star
76

url

Parse, build and manipulate URL's
PHP
659
star
77

laravel-html

Painless html generation
PHP
654
star
78

laravel-health

Check the health of your Laravel app
PHP
648
star
79

laravel-event-projector

Event sourcing for Artisans ๐Ÿ“ฝ
PHP
642
star
80

laravel-server-side-rendering

Server side rendering JavaScript in your Laravel application
PHP
636
star
81

vue-tabs-component

An easy way to display tabs with Vue
JavaScript
626
star
82

macroable

A trait to dynamically add methods to a class
PHP
621
star
83

laravel-csp

Set content security policy headers in a Laravel app
PHP
614
star
84

laravel-blade-javascript

A Blade directive to export variables to JavaScript
PHP
608
star
85

laravel-cors

Send CORS headers in a Laravel application
PHP
607
star
86

laravel-translation-loader

Store your translations in the database or other sources
PHP
602
star
87

vue-table-component

A straight to the point Vue component to display tables
JavaScript
591
star
88

activitylog

A very simple activity logger to monitor the users of your website or application
PHP
586
star
89

http-status-check

CLI tool to crawl a website and check HTTP status codes
PHP
584
star
90

phpunit-snapshot-assertions

A way to test without writing actual testย cases
PHP
584
star
91

laravel-queueable-action

Queueable actions in Laravel
PHP
584
star
92

laravel-short-schedule

Schedule artisan commands to run at a sub-minute frequency
PHP
579
star
93

laravel-onboard

A Laravel package to help track user onboarding steps
PHP
579
star
94

freek.dev

The sourcecode of freek.dev
PHP
571
star
95

server-side-rendering

Server side rendering JavaScript in a PHP application
PHP
568
star
96

laravel-pdf

Create PDF files in Laravel apps
PHP
563
star
97

string

String handling evolved
PHP
558
star
98

ray

Debug with Ray to fix problems faster
PHP
540
star
99

laravel-http-logger

Log HTTP requests in Laravel applications
PHP
538
star
100

laravel-blade-x

Use custom HTML components in your Blade views
PHP
533
star