Skip to content

Using non-default mailers #16

@ejunker

Description

@ejunker

I have multiple mailers configured in my config/mail.php with the default set to sendmail

    'default' => env('MAIL_MAILER', 'sendmail'),

    'mailers' => [
        'sendmail' => [
            'transport' => 'sendmail',
            'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -bs -i'),
        ],

        'sparkpost' => [
            'transport' => 'sparkpost',
        ],

If I have code that uses a specific mailer to send mail I do something like this in my test:

class MailableTest extends TestCase
{
    use WithMailInterceptor;

    public function test_example(): void
    {
        $this->interceptMail();
        Mail::mailer('sparkpost')->send(new MyMailable());
        $this->assertNotEmpty($this->interceptedMail());
    }
}

This test fails. I discovered if I change:

    public function interceptedMail(): Collection
    {
        return app('mailer')->getSymfonyTransport()
            ->messages()
            ->map(function (SentMessage $message) {
                return new AssertableMessage($message->getOriginalMessage());
            });
    }

to using the mail manager and allow specifying the mailer like this:

    public function interceptedMail(?string $mailer = null): Collection
    {
        return app('mail.manager')->mailer($mailer)->getSymfonyTransport()
            ->messages()
            ->map(function (SentMessage $message) {
                return new AssertableMessage($message->getOriginalMessage());
            });
    }

and then in my test do this it works:

$this->assertNotEmpty($this->interceptedMail('sparkpost'));

Is there a better way to handle this? This was just an example test; in the real world this would be a feature test where I am not sending the mailable directly in the test but rather making a request to my app that generates the email.

I was considering creating a PR with this change, but I wasn't sure how to add a test that covers this functionality.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions