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. Note that these emails don't support HTML, any HTML will be rendered literally.

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')
);

These plain-text emails are a good way to notify yourself when a side-project needs attention. For example, this website sends out a notification if a new redirect is created after a deployment:

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(),
        ]);
    }
}