Mailable classes help you send emails easily by organizing email content and settings in one place.
Mailable classes in Laravel
php artisan make:mail ClassName // Inside the Mailable class public function build() { return $this->view('emails.example') ->with(['key' => 'value']) ->subject('Email Subject'); }
Use php artisan make:mail to create a new Mailable class.
The build method defines the email content, view, and subject.
<?php namespace App\Mail; use Illuminate\Mail\Mailable; class WelcomeMail extends Mailable { public function build() { return $this->view('emails.welcome') ->subject('Welcome to Our Site'); } }
<?php namespace App\Mail; use Illuminate\Mail\Mailable; class OrderShipped extends Mailable { public $order; public function __construct($order) { $this->order = $order; } public function build() { return $this->view('emails.shipped') ->with(['order' => $this->order]) ->subject('Your Order Has Shipped'); } }
This example shows a Mailable class that sends a notification email with dynamic content passed through the constructor. The email view receives the content to display.
<?php namespace App\Mail; use Illuminate\Mail\Mailable; class NotificationMail extends Mailable { public $messageContent; public function __construct($messageContent) { $this->messageContent = $messageContent; } public function build() { return $this->view('emails.notification') ->with(['content' => $this->messageContent]) ->subject('Important Notification'); } } // Usage example in a controller or route: use App\Mail\NotificationMail; use Illuminate\Support\Facades\Mail; $message = 'Hello! This is a test notification.'; Mail::to('user@example.com')->send(new NotificationMail($message));
Always create a Blade view file for your email content inside resources/views/emails/.
You can chain methods like cc(), bcc(), and attach() inside build() to customize the email further.
Test emails locally using tools like Mailtrap or log driver to avoid sending real emails during development.
Mailable classes organize email logic and content in one place.
Use the build() method to set the view, subject, and data.
Pass dynamic data via the constructor to customize emails.