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>