How to Send Emails in Laravel with Mailable

How to Send Emails in Laravel with Mailable

How to Send Emails in Laravel with Mailable

Laravel's Mailable system makes sending emails clean and testable. Here's how to set it up from scratch.

Step 1 — Configure Mail Driver

In your .env file, set your mail driver. For local development, log or mailtrap work great:

MAIL_MAILER=smtp
MAIL_HOST=sandbox.smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your_username
MAIL_PASSWORD=your_password
MAIL_FROM_ADDRESS="[email protected]"
MAIL_FROM_NAME="${APP_NAME}"

Step 2 — Create a Mailable

php artisan make:mail OrderShipped --markdown=emails.orders.shipped

Step 3 — Define the Mailable Class

// app/Mail/OrderShipped.php
namespace App\Mail;

use App\Models\Order;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;

class OrderShipped extends Mailable
{
    public function __construct(public Order $order) {}

    public function envelope(): Envelope
    {
        return new Envelope(subject: "Your order #{$this->order->id} has shipped!");
    }

    public function content(): Content
    {
        return new Content(markdown: 'emails.orders.shipped');
    }
}

Step 4 — Write the Blade Template

{{-- resources/views/emails/orders/shipped.blade.php --}}
<x-mail::message>
# Your Order Has Shipped

Hi {{ $order->customer_name }},

Your order **#{{ $order->id }}** is on its way!

<x-mail::button :url="route('orders.show', $order)">
Track Your Order
</x-mail::button>

Thanks for shopping with us!
</x-mail::message>

Step 5 — Send the Email

use App\Mail\OrderShipped;
use Illuminate\Support\Facades\Mail;

Mail::to($order->customer_email)->send(new OrderShipped($order));

// Queue it to avoid blocking the request
Mail::to($order->customer_email)->queue(new OrderShipped($order));
All Comments