Search code examples
phplaravellaravel-5

Laravel override mail to automatically add plain text version


I'm making some changes in my Laravel app to automatically add plain text version to my e-mails.. I'm doing that by using the library

https://packagist.org/packages/html2text/html2text

I would get the text version by running

\Html2Text\Html2Text::convert($content)

Now I want to override laravels Mailable.php buildView() function to automaticaly generate the text. My question is: how to properly override it? Where can I redeclare it?


Solution

  • The Mailer is defined by the Mailer Service Provider, you can see the registration of it in your config/app.php under 'providers', where you will see this:

    \Illuminate\Mail\MailServiceProvider::class,
    

    So, all you need to do, is remove the MailServiceProvider registration and create your own Provider based on that one with your changes and register yours.

    Make sure you implement the Illuminate\Contracts\Mail\Mailer contract.

    But you don't need to!

    The mailer that comes with Laravel already support sending the HTML and Plain versions of your email.

    The Mailer::send() method's first argument is @param string|array $view, where you usually send the view name of the HTML version of your email, but, you can instead send an array like this...

    Mailer::send([
        'html' => 'my-mails.notification-in-html',
        'text' => 'my-mails.notification-in-text',
      ], $data, $callback);
    

    Where you could even define a different text and remove things that you would not put in your plain text version, or adjust a different signature that looks good on plain, and also format things different.

    For more information you can look at the parseView() in Illuminate\Mail\Mailer class.

    So, there you have it, 2 options:

    • Create your own Mailer and register it instead of the default one
    • or just call the mailer with an array of views.