Easily Test Email with MailThief

Easily Test Email with MailThief

MailThief is a new package by Tighten Co. that provides a fake mailer for your Laravel application. This makes it easy to test email without actually sending any.

To better explain how this package works take a look at the following example from the project.

First, pretend you have a registration route that sends the user a welcome email:

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('noreply@example.com');
        $m->bcc('notifications@example.com');
    });

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

Typically testing this would be pretty difficult, but with MailThief it’s simple:

use MailThief\Facades\MailThief;

class RegistrationTest extends TestCase
{
    public function test_new_users_are_sent_a_welcome_email()
    {
        // Block and intercept outgoing mail, important!
        MailThief::hijack();

        $this->post('register', [
            'name' => 'John Doe',
            'email' => 'john@example.com',
            'password' => 'secret',
        ]);

        // Check that an email was sent to this email address
        $this->assertTrue(MailThief::hasMessageFor('john@example.com'));

        // BCC addresses are included too
        $this->assertTrue(MailThief::hasMessageFor('notifications@example.com'));

        // Make sure the email has the correct subject
        $this->assertEquals('Welcome to my app!', MailThief::lastMessage()->subject);

        // Make sure the email was sent from the correct address
        // (`from` can be a list, so we return it as a collection)
        $this->assertEquals('noreply@example.com', MailThief::lastMessage()->from->first());
    }
}

You can grab the package from Github and if you’d like to learn more about the thought process behind building MailThief check out this post and video by Adam Wathan.


Filed in: Laravel Packages / Email / Testing


Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Laravel + Vue.JS developer
Remote or in Toronto Canada
Star Dot Hosting Inc
Full Stack or Back-End Developer
Alexandria, VA; Tallahassee, FL; Orlando, FL
Marketing for Change
Senior Quality Assurance Engineer
Remote
Bisnow Media
Senior PHP/Laravel Developer: Your Dream Work Environment
Remote
iPhone Photography School
Senior Software Engineer
Remote or San Francisco
Curology
Laravel Developer
Las Vegas, NV
V Shred
R&D Developer
Denver, CO
booj