A fake mailer for Laravel Applications for testing mail.

Overview

Github Actions Status MailThief Logo

MailThief

MailThief is a fake mailer for Laravel applications (5.0+) that makes it easy to test mail without actually sending any emails.

Note:

Due to changes in the way mail testing is handled by Laravel; MailThief is not needed for recent versions of the framework. MailThief will remain compatible with Laravel up to version 5.5.

Quickstart

Installation:

composer require tightenco/mailthief --dev

Example route:

Route::post('register', function () {
    // <snip> Validation, create account, etc. </snip>

    Mail::send('emails.welcome', [], function ($m) {
        $email = request('email');
        $m->to($email);
        $m->subject('Welcome to my app!');
        $m->from('[email protected]');
        $m->bcc('[email protected]');
        $m->getHeaders()->addTextHeader('X-MailThief-Variables', 'mailthief');
    });

    // <snip> Return response </snip>
});

If you're copying this sample test, remember to create an email view at resources/views/emails/welcome.blade.php.

Example test:

use MailThief\Testing\InteractsWithMail;

class RegistrationTest extends TestCase
{
    // Provides convenient testing traits and initializes MailThief
    use InteractsWithMail;

    public function test_new_users_are_sent_a_welcome_email()
    {
        $this->post('register', [
            'name' => 'John Doe',
            'email' => '[email protected]',
            'password' => 'secret',
        ]);

        // Check that an email was sent to this email address
        $this->seeMessageFor('[email protected]');

        // BCC addresses are included too
        $this->seeMessageFor('[email protected]');

        // Make sure the email has the correct subject
        $this->seeMessageWithSubject('Welcome to my app!');

        // Make sure the email was sent from the correct address
        $this->seeMessageFrom('[email protected]');

        // Make sure a given header is set on an email
        $this->seeHeaders('X-MailThief-Variables');

        // Make sure the header is set to a given value
        $this->seeHeaders('X-MailThief-Variables', 'mailthief');

        // Make sure the email contains text in the body of the message
        // Default is to search the html rendered view
        $this->assertTrue($this->lastMessage()->contains('Some text in the message'));
        // To search in the raw text
        $this->assertTrue($this->lastMessage()->contains('Some text in the message', 'raw'));
    }
}

MailThief supports just about everything you can do with the regular Laravel Mailer and Message classes. More detailed documentation is coming soon, but in the mean time, explore the MailThief and Message classes to get an idea of what's available.

If you’re using the new Mailables syntax in Laravel 5.3, you can use the native mail assertions. But if you’re using the classic mail syntax in any version of Laravel, MailThief is still your best option.

Comments
  • Adds global `from` support

    Adds global `from` support

    This PR is based on the branch on PR #41 that bumps the Illuminate package version.

    Laravel has a global from feature when sending emails, this is a feature that lets you specified the name and email address that will be used for the from field in all emails that the application sends when no from gets specified in the message.,

    This PR adds support for that global from functionality.

    opened by gpopoteur 12
  • Test to prove #81 was actually fixed!

    Test to prove #81 was actually fixed!

    Okay so bear with me on this one! I only added the minimum required necessities to get this test to pass. If you check out this branch and change getMailer to return $this->mailer ?: MailThief::getFacadeRoot() then you'll see this break.

    Let me know if I didn't follow naming conventions, style guide, etc!

    opened by FatBoyXPC 9
  • Add Messages Accessors

    Add Messages Accessors

    I find myself in situations where other messages may have been sent after the one that I'm interested in making an assertion about. I can continue to have these locally, but they should be of more general use to others.

    In particular, this should help with #53. The assertion methods may easily be rewritten to take advantage of these methods to become more general in which email gets matched.

    opened by mcordingley 9
  • Lumen support

    Lumen support

    Pulling in the entire Laravel Framework causes issues when trying to use this package in a Lumen application. These incompatibilities can be avoided by explicitly requiring only the necessary sub-packages, namely illuminate/mail and illuminate/view.

    I have tested this with a fresh Lumen installation as well as an existing Lumen application.

    opened by ksassnowski 9
  • Laravel 5.5 MailQueue Contract Change

    Laravel 5.5 MailQueue Contract Change

    Hey, I just wanted to point out a breaking change in laravel v5.5 that causes this package to no longer function. The signatures for at least the queue(), onQueue(), and queueOn() functions has changed from laravel v5.4.

    • https://github.com/illuminate/contracts/blob/5.4/Mail/MailQueue.php#L16 vs.
    • https://github.com/illuminate/contracts/blob/5.5/Mail/MailQueue.php#L14

    In laravel v5.5 only Mailables can be queued now:

    • https://github.com/illuminate/mail/blob/5.5/Mailer.php#L351-L358

    I believe the solution will be rather simple:

    • Update your composer.json in the next release to require ^5.5 of the illuminate dependencies.
    "require": {
        "illuminate/mail": "^5.5",
        "illuminate/view": "^5.5"
    },
    
    • Update the method signatures on MailThief object to match the MailQueue contract changes
    • Update any associated tests for queues to only test queueing Mailables

    If you need any assistance with a PR, I'd be happy to help. However, it is hard to tell how active this repo is until I post this. So for now, I'll just resort to logging test emails and disable usage of this package.

    opened by wells 8
  • Support for custom mail headers

    Support for custom mail headers

    I use Sendgrid to send out our mail. One feature they allow is sending certain headers to categorize mail or send other options. To set the headers I have to get the underlying swift message, which of course means I cannot use MailThief. However it would also be great to be able to check for certain headers during our tests. Do you think this is functionality that should be added? If so I could look into stubbing that out. Obviously the whole SwiftMailer would be too extensive, but would headers be a feature we would want to be able to fake some implementation for?

    opened by djohnston08 7
  • Mailthief doesn't seem to be working with Illuminate/Foundation/Auth/ResetsPasswords.php

    Mailthief doesn't seem to be working with Illuminate/Foundation/Auth/ResetsPasswords.php

    Hi,

    When trying to test my password reset emails I get this error:

    A request to [http://xxxxxxxxxxxxxxx/password/email] failed. Received status code [500].
    
    Caused by
     Symfony\Component\Debug\Exception\FatalThrowableError: Type error: Argument 1 passed to App\Http\Controllers\Auth\PasswordController::Illuminate\Foundation\Auth\{closure}() must be an instance of Illuminate\Mail\Message, instance of MailThief\Message given
    

    All other email testing is fine. It seems that mailthief doesn't play nice with Illuminate/Foundation/Auth/ResetsPasswords.php.

    help wanted 
    opened by stefro 6
  • HTML Character Codes

    HTML Character Codes

    I noticed today that MT was failing out on HTML character codes when doing the ->contains() assertion.

    Seeing as Laravel's tools (this was using notifications) default to rendering character codes should that be looked at? It would just be a matter of wrapping the "Contains" assertion in the e() helper function.

    hacktoberfest 
    opened by psaunders 5
  • Error: Call to a member function first() on null

    Error: Call to a member function first() on null

    Hey,

    I have the following in my test:

    $this->seeMessageFor($user->email);
    $this->seeMessageWithSubject('Reset Password');
    // Make sure the email was sent from the correct address
    $this->seeMessageFrom(config('mail.from.address'));
    

    However, the seeMessageFrom leads the the error:

    Error: Call to a member function first() on null
    /Users/lukasoppermann/Code/fs-cms/vendor/tightenco/mailthief/src/Testing/InteractsWithMail.php:63
    /Users/lukasoppermann/Code/fs-cms/tests/functional/LoginPageTest.php:96
    

    Line 96 is $this->seeMessageFrom(config('mail.from.address')); however, the address from config is correct and even replacing it with a string does not help.

    Removing this line makes the test pass.

    I just noticed that if I dd($this->lastMessage()) the from is null. But in the log file, there is a from part.

    Any ideas?

    opened by lukasoppermann 5
  • Laravel chainable helper methods

    Laravel chainable helper methods

    Hello!

    In my Laravel 5.2 app I created a little trait with some helpers, to call MailThief asserts in the same way as the see() and seeInDatabase() methods. Perhaps it could be interesting to add helpers like this to your package?

    use MailThief\Facades\MailThief;
    
    trait InterceptsEmail
    {
        /** @before */
        protected function interceptEmails()
        {
            MailThief::hijack();
        }
    
        protected function seeEmailFor($email)
        {
            $this->assertTrue(
                MailThief::hasMessageFor($email),
                sprintf('No e-mail was sent to "%s".', $email)
            );
    
            return $this;
        }
    
        protected function seeEmailSubject($subject)
        {
            $this->assertEquals(
                $subject, MailThief::lastMessage()->subject,
                sprintf('The e-mail subject does not match "%s".', $subject)
            );
    
            return $this;
        }
    
        protected function seeInEmailSubject($subject)
        {
            $this->assertContains(
                $subject, MailThief::lastMessage()->subject,
                sprintf('The e-mail subject does not contain the text "%s".', $subject)
            );
    
            return $this;
        }
    }
    

    This allows me to run tests like this:

    use Illuminate\Foundation\Testing\DatabaseMigrations;
    
    class RegistrationTest extends TestCase
    {
        use DatabaseMigrations;
        use InterceptsEmail;
    
        /** @test */
        public function a_user_receives_an_activation_mail_after_registering()
        {
            $userData = [
                'first_name' => 'John',
                'last_name' => 'Doe',
                'email' => '[email protected]',
            ];
    
            $this->visit('/nl/login')
                ->type($userData['first_name'], 'first_name')
                ->type($userData['last_name'], 'last_name')
                ->type($userData['email'], 'email')
                ->check('agree')
                ->press('Register');
    
            $this->see('Thanks')
                ->seeEmailFor($userData['email'])
                ->seeInEmailSubject('Activate')
                ->seeInDatabase('activations', $userData);
        }
    }
    
    opened by ivanvermeyen 5
  • [Bugfix] Laravel 5.5 Compatibility

    [Bugfix] Laravel 5.5 Compatibility

    This pull request resolves issues with the latest commit to support Laravel 5.5.

    Please reference the most recent comments in Issue #76 to see a detailed explanation on how this fixes the current release for laravel v5.5.

    opened by wells 4
Releases(v0.3.14)
Owner
Tighten
Tighten
A project to add Psalm support for Drupal for security testing, focused only on taint analysis.

psalm-plugin-drupal A Drupal integration for Psalm focused on security scanning (SAST) taint analysis. Features Stubs for sinks, sources, and sanitize

Samuel Mortenson 38 Aug 29, 2022
A static analysis tool for finding errors in PHP applications

Psalm Psalm is a static analysis tool for finding errors in PHP applications. Installation To get started, check out the installation guide. Live Demo

Vimeo 5k Jan 2, 2023
Rector upgrades rules for Laravel

Rector Rules for Laravel See available Laravel rules Install This package is already part of rector/rector package, so it works out of the box. All yo

Rector 185 Dec 30, 2022
Automagically generate UML diagrams of your Laravel code.

Laravel UML Diagram Generator Automagically generate UML diagrams of your Laravel code. Installation To install LTU via composer, run the command: com

Andy Abi Haidar 93 Jan 1, 2023
A toolbar for Laravel Telescope, based on the Symfony Web Profiler.

Laravel Telescope Toolbar Extends Laravel Telescope to show a powerful Toolbar See https://github.com/laravel/telescope Install First install Telescop

Fruitcake 733 Dec 30, 2022
A rate limiter for Laravel

Laravel Throttle Laravel Throttle was created by, and is maintained by Graham Campbell, and is a rate limiter for Laravel. Feel free to check out the

Graham Campbell 673 Dec 30, 2022
A package to help you clean up your controllers in laravel

?? Laravel Terminator ?? ?? "Tell, don't ask principle" for your laravel controllers What this package is good for ? Short answer : This package helps

Iman 241 Oct 10, 2022
Learn how to set up a fake authentication web page on a fake WiFi network.

Evil Twin - Mark VII Learn how to set up a fake authentication web page on a fake WiFi network. Read the comments in these two files to get a better u

Ivan Šincek 44 Dec 13, 2022
A drop in fake logger for testing with the Laravel framework.

Log fake for Laravel A bunch of Laravel facades / services are able to be faked, such as the Dispatcher with Bus::fake(), to help with testing and ass

Tim MacDonald 363 Dec 19, 2022
A Laravel package to check if you can send e-mail through a given mailserver in name of a given e-mail address

A Laravel package to check if you can send e-mail through a given mailserver in name of a given e-mail address Mail spf checker A Laravel package to c

Dieter Coopman 110 Dec 16, 2022
A mail driver to quickly preview mail

A mail driver to quickly preview mail This package can display a small overlay whenever a mail is sent. The overlay contains a link to the mail that w

Spatie 1k Dec 22, 2022
A mail driver to quickly preview mail

A mail driver to quickly preview mail This package can display a small overlay whenever a mail is sent. The overlay contains a link to the mail that w

Spatie 1k Jan 4, 2023
A testing package for intercepting mail sent from Laravel

Laravel Mail Intercept A testing package for intercepting mail sent from Laravel This testing suite intercepts Laravel Mail just before they are sent

Kirschbaum Development Group, LLC 91 Oct 18, 2022
Laravel Mail Credentials switcher for Budget Laravel Applications

Laravel Mail Switcher Laravel Mail Credentials Switcher is a library which helps you to: Manage your Mail Service Credentials Configure the Laravel's

(Seth) Phat Tran 34 Dec 24, 2022
Laravel mailer which will catch all the sent emails and show them on an application view.

Laravel Web Mailer This package contains a web mailer which will catch all the sent emails. Then, you can view it visiting the route /web-inbox. The e

Creagia 54 Dec 16, 2022
SimpleTest is a framework for unit testing, web site testing and mock objects for PHP

SimpleTest SimpleTest is a framework for unit testing, web site testing and mock objects for PHP. Installation Downloads All downloads are stored on G

SimpleTest 147 Jun 20, 2022
The Mailer component helps sending emails

Mailer Component The Mailer component helps sending emails. Getting Started $ composer require symfony/mailer use Symfony\Component\Mailer\Transport;

Symfony 1.1k Jan 7, 2023
Provides Amazon SES integration for Symfony Mailer

Amazon Mailer Provides Amazon SES integration for Symfony Mailer. Resources Contributing Report issues and send Pull Requests in the main Symfony repo

Symfony 49 Nov 7, 2022
Yii Framework Symfony Mailer Integration

Yii Mailer Library - Symfony Mailer Extension This package is an adapter for yiisoft/mailer relying on symfony/mailer. Requirements PHP 7.4 or higher.

Yii Software 9 Oct 26, 2022