← Other topics

Send emails in Laravel without a Mailable class

Video Notes

The “proper“ way to send emails in Laravel is to generate Mailable classes for each email you want to send.

Sometimes, though, it can be useful to quickly send an email without the overhead of an additional class.

This can be done using the Mail facades raw (for plain text emails) or html (for emails with HTML code) methods. The code below shows examples of each, including an example where the body of the email is generated from a View file.

Example:

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Mail;

class DemoController extends Controller
{
    public function index()
    {
        $email = 'test@gmail.com';
        $subject = 'This is the subject';
        $body = '<h1>This is the body of the email...</h1>';

        # EXAMPLE 1) Send the plain text email
        Mail::raw($body, function ($message) use ($email, $subject) {
            $message->to($email)
                    ->subject($subject . ' plain text');
        });

        # EXAMPLE 2) Send the HTML email
        Mail::html($body, function ($message) use ($email, $subject) {
            $message->to($email)
                    ->subject($subject . ' html');
        });

        # EXAMPLE 3) Send the HTML email using a View
        $body = view('demo')->render();
        Mail::html($body, function ($message) use ($email, $subject) {
            $message->to($email)
                    ->subject($subject . ' html from a View');
        });
    }
}

Contents of /resources/views/demo.blade.php:

<h1>This is my email content as written in a View file</h1>

Unlock all the notes for $4

No subscriptions, no auto-renewals.

Just a simple one-time payment that helps support my free, to-the-point videos without sponsered ads.

Unlocking gets you access to the notes for this video plus all 200+ guides on this site.

Your support is appreciated. Thank you!

Payment Info

/
$4 6 months
$25 forever
Please check the form for errors
Questions? help@codewithsusan.com
← Other topics