Plain text emails are still very important these days. For many of them, however, it is pointless to write a plain text version as long as it can be automatically generated from HTML format.
- step: Install html2text:
composer require soundasleep/html2text
- step: Create file TextMailBuilder.php:
This trait contains a buildView method that overwrites the original method and will generate text for the email only if you do not use your own view for the plain text version of the email.
Create Traits folder in app/Mails, then create TextMailBuilder.php file, then place the entire code to this file:
<?php
namespace App\Mail\Traits;
use Illuminate\Contracts\View\Factory as ViewFactory;
use Illuminate\Support\HtmlString;
use Soundasleep\Html2Text;
trait TextMailBuilder
{
protected function buildView()
{
if (isset($this->html)) {
if (! $this->textView) {
$plainText = Html2Text::convert($this->html);
$text = new HtmlString($plainText);
} else {
$text = $this->textView;
}
return array_filter([
'html' => new HtmlString($this->html),
'text' => $text,
]);
}
if (isset($this->markdown)) {
return $this->buildMarkdownView();
}
if (isset($this->view, $this->textView)) {
return [$this->view, $this->textView];
} elseif (isset($this->textView)) {
return ['text' => $this->textView];
}
return $this->view;
}
}
- step: Import TextMailBuilder trait to your Mailables:
<?php
namespace App\Mail;
use App\Mail\Traits\TextMailBuilder;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class OrderReceived extends Mailable
{
use Queueable;
use SerializesModels;
use TextMailBuilder;
...
}
Comments (0)