Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get messages sent with the `array` mail driver?

Starting from version 5.7 Laravel suggests to use the array driver for Mail during testing:

Unfortunately, the documentation tells nothing about this driver. According to the source code, the driver stores all the messages in memory without actually sending them. How to get the stored "sent" messages during unit testing (in order to check them)?

like image 646
Finesse Avatar asked Sep 05 '18 04:09

Finesse


2 Answers

EDIT: With Laravel 9+, use:

$emails = app()->make('mailer')->getSymfonyTransport()->messages();
dd($emails);

Be sure your mail driver is set to array in your .env or phpunit.xml file.

With Laravel 7+ or if you get error Target class [swift.transport] does not exist use this to get the list of emails sent with the array driver:

$emails = app()->make('mailer')->getSwiftMailer()->getTransport()->messages();

$count = $emails->count();
$subject = $emails->first()->getSubject();
$to = $emails->first()->getTo();
$body = $emails->first()->getBody();
like image 170
Alan Reed Avatar answered Oct 05 '22 11:10

Alan Reed


Call app()->make('swift.transport')->driver()->messages(). The return value is a collection of Swift_Mime_SimpleMessage objects.

An example of a full PHPUnit test:

public function testEmail()
{
    Mail::to('[email protected]')->send(new MyMail);

    $emails = app()->make('swift.transport')->driver()->messages();
    $this->assertCount(1, $emails);
    $this->assertEquals(['[email protected]'], array_keys($emails[0]->getTo()));
}
like image 40
Finesse Avatar answered Oct 05 '22 11:10

Finesse