Send a raw plain text email with Laravel

Published on

Sometimes you just want to send a quick email without having to create a new class. Laravel's Mail::raw() is perfect for this, it accepts a string as the body and then sends the email right away.

use Illuminate\Mail\Message;
use Illuminate\Support\Facades\Mail;

// Note: can't use HTML here, any HTML tags will be rendered literally.
Mail::raw(
    <<<TEXT
    Hi,

    Just a quick heads up, (...)

    TEXT,
    fn (Message $mail) => $mail->to('email@example.com')->subject('The subject')
);

I usually use these types of plain-text emails when one of my side-projects needs attention. For example, this website automatically creates a redirect when I change the slug of a post. When a redirect is created it sends me an email to double-check the new redirect:

use Illuminate\Mail\Message;
use Illuminate\Support\Facades\Mail;

class NotifyAboutNewRedirectsJob extends BaseJob implements ShouldQueue
{
    public function handle()
    {
        if (PostRedirect::whereNull('notified_at')->doesntExist()) {
            return;
        }

        $url = route('admin.dashboard.index');

        Mail::raw(
            <<<TEXT
            Hi,

            A new redirect was created, go double check: $url

            TEXT,
            fn (Message $mail) => $mail->to('me@example.com')->subject('A new redirect was created')
        );

        PostRedirect::whereNull('notified_at')->update([
            'notified_at' => now(),
        ]);
    }
}