PLATFORM
  • Tails

    Create websites with TailwindCSS

  • Blocks

    Design blocks for your website

  • Wave

    Start building the next great SAAS

  • Pines

    Alpine & Tailwind UI Library

  • Auth

    Plug'n Play Authentication for Laravel

  • Designer comingsoon

    Create website designs with AI

  • DevBlog comingsoon

    Blog platform for developers

  • Static

    Build a simple static website

  • SaaS Adventure

    21-day program to build a SAAS

Written By
Views

Automatically generate plain text e-mails without view in Laravel 5+

Automatically generate plain text e-mails without view in Laravel 5+

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.

  1. step: Install html2text:
composer require soundasleep/html2text
  1. 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;
    }
}
  1. 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)

loading comments