← 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>

If this info helped you out you can say thanks and support future content by clicking my Amazon affiliate link: https://amzn.to/3UtgnYk. If you make a purchase on Amazon within 24 hours of clicking the link I may receive a micro-commission and it costs you nothing extra. Any income from these sales goes directly to supporting me in making new videos and guides. Thank you for your support!

← Other topics