Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 67 ยท Queues, Events and Notifications

Sending Mail

Send email in Laravel with Mailable classes: envelope, content, Markdown mail, attachments, queued mail, the log driver for local work, and Mail::fake.

Almost every web app sends email: welcome messages, receipts, password resets, weekly digests. Laravel treats an email as an object. You write a class that describes one message, a mailable, and hand it to the mail system, which builds it and delivers it through whatever service you configured. The same class works with SMTP, a provider API or a local log file. You change the transport in configuration, not in code.

This lesson covers writing mailables, Markdown templates, attachments, queuing, local development and testing. For notifications that can go to several channels, see the next lesson; mail is the building block under its mail channel.

Laravel cannot run on this site, so Laravel code blocks are read-only. The runnable examples are plain PHP stand-ins that show what a mailable does, and each section says which is which.

Mailers and configuration

Mail settings live in config/mail.php and .env. A mailer is one transport configuration, and MAIL_MAILER picks the default one. The built-in options include smtp, ses, postmark, resend, sendmail, log and array. A failover mailer tries several in turn.

INI
MAIL_MAILER=smtp
MAIL_HOST=smtp.example.com
MAIL_PORT=587
MAIL_FROM_ADDRESS="[email protected]"
MAIL_FROM_NAME="${APP_NAME}"

For local development use MAIL_MAILER=log. Nothing is sent: the complete raw message is written to storage/logs/laravel.log, where you can read headers, subject and body. This very site does exactly that. Tools such as Mailpit or Herd's mail service catch SMTP mail in a local inbox with a preview, which is nicer once you care about layout. The array mailer keeps messages in memory and is used by tests.

Writing a mailable

Terminal
php artisan make:mail OrderShipped
PHP
<?php

namespace App\Mail;

use App\Models\Order;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;

class OrderShipped extends Mailable
{
    use Queueable, SerializesModels;

    public function __construct(public Order $order)
    {
    }

    public function envelope(): Envelope
    {
        return new Envelope(
            subject: "Order #{$this->order->number} has shipped",
        );
    }

    public function content(): Content
    {
        return new Content(
            view: 'mail.orders.shipped',
            with: ['trackingUrl' => $this->order->tracking_url],
        );
    }

    public function attachments(): array
    {
        return [];
    }
}

A mailable has three jobs, each with its own method:

  • envelope() returns the envelope: subject, and optionally from, replyTo, cc, bcc and tags. If you omit from, the global MAIL_FROM_* values are used.
  • content() returns the content: which view renders the HTML (view), an optional plain-text view (text), a Markdown template (markdown), and data for the view (with). Public properties of the mailable are available to the view automatically.
  • attachments() returns the files to attach.

Sending it is one line:

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

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

Mail::to('[email protected]')
    ->cc($manager)
    ->bcc('[email protected]')
    ->send(new OrderShipped($order));

to() accepts an email string, a user model with an email property, or a collection of recipients. A model needs its name and email properties so Laravel can set the display name.

Views and Markdown mail

An HTML email is an ordinary Blade view, but email clients are old and quirky: no modern CSS layout, inline styles, tables for structure. Writing that by hand is painful, so Laravel ships Markdown mail: you write Markdown with a few Blade components and get a responsive, tested HTML layout plus an automatic plain-text version.

Terminal
php artisan make:mail OrderShipped --markdown=mail.orders.shipped
BLADE
<x-mail::message>
# Your order has shipped

Hi {{ $order->customer->name }}, order **#{{ $order->number }}** is on its way.

<x-mail::button :url="$trackingUrl">
Track the parcel
</x-mail::button>

<x-mail::table>
| Item | Qty |
| :--- | --: |
@foreach ($order->items as $item)
| {{ $item->name }} | {{ $item->quantity }} |
@endforeach
</x-mail::table>

Thanks,<br>
{{ config('app.name') }}
</x-mail::message>

The components message, button, panel and table are the toolkit. Indent nothing inside them, because Markdown treats indented lines as code. To restyle, publish the templates with php artisan vendor:publish --tag=laravel-mail and edit the theme CSS. Always escape user data with {{ }} as usual, and remember that email content has to stay readable if images are blocked.

Attachments

PHP
use Illuminate\Mail\Mailables\Attachment;

public function attachments(): array
{
    return [
        Attachment::fromPath(storage_path('app/invoices/'.$this->order->number.'.pdf'))
            ->as('invoice.pdf')
            ->withMime('application/pdf'),

        Attachment::fromStorageDisk('s3', "receipts/{$this->order->id}.pdf"),

        Attachment::fromData(fn () => $this->renderCsv(), 'items.csv')
            ->withMime('text/csv'),
    ];
}

fromPath reads a local file, fromStorage and fromStorageDisk use the filesystem disks, and fromData attaches generated bytes without creating a temporary file. Watch the size: many mail servers reject messages above 10 to 25 MB, so for big files send a link instead. To show an image inside the HTML, use embedded images ($message->embed($path) in the view) rather than a remote URL.

A mailable builder

A mailable is basically a value object that knows how to build a message. This stand-in has the same three parts: envelope, content and attachments, then renders a raw-looking message like the log driver would write.

PHP A mailable builder stand-in

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice that the name is escaped before it goes into the HTML, and that the plain-text part is derived from the HTML. Laravel's Markdown mail does the same in a more careful way.

Queued mail

Delivering mail means talking to a remote server, which is slow and sometimes fails. Do not make visitors wait for it. Queue the message:

PHP
Mail::to($order->customer)->queue(new OrderShipped($order));
Mail::to($order->customer)->later(now()->addHour(), new OrderShipped($order));

Both push a queued job that sends the mail in a worker, with retries. To make a mailable always queued, implement Illuminate\Contracts\Queue\ShouldQueue on it, and then send() queues too. Use ->onQueue('mail') to route to a dedicated queue. If you queue mail inside a database transaction, call afterCommit() so the worker does not run before the data exists.

Testing mail

Tests should never send mail. Mail::fake() swaps the mailer for a recorder:

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

it('emails the customer when an order ships', function () {
    Mail::fake();

    $order = Order::factory()->create();
    $this->post("/orders/{$order->id}/ship");

    Mail::assertSent(OrderShipped::class, function (OrderShipped $mail) use ($order) {
        return $mail->hasTo($order->customer->email)
            && $mail->order->is($order);
    });
    Mail::assertNothingQueued();
});

Use assertQueued when the code queues, assertNotSent for the negative case and assertSentCount to count. You can also render a mailable without sending to test its text: (new OrderShipped($order))->assertSeeInHtml('Track the parcel').

A stand-in for the recording idea, with both immediate and queued sending:

PHP A fake mailer with an outbox

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Practical advice

  • Authenticate your domain. Set up SPF, DKIM and DMARC with your provider, or your mail lands in spam.
  • Use a provider, not your web server. Postmark, Resend, Amazon SES and similar services handle reputation and bounces.
  • Always queue anything that is not needed in the same request.
  • Keep content safe. Escape data, never put secrets or full tokens in mail that you cannot rotate, and use signed URLs for links that act on behalf of a user (see Fortify and verification).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which setting lets you develop locally without sending any real email while still seeing each message?

    The log mailer writes the full message to the Laravel log file. Nothing leaves your machine, and you can read the headers and body.
  2. 2. In a Laravel 13 mailable, which method sets the subject line?

    envelope() returns an Envelope with the subject, from, replyTo, cc and bcc. content() chooses the view and data, and attachments() lists files.
  3. 3. Why is Mail::queue() usually better than Mail::send() inside a controller?

    Delivery is a slow remote call that can fail. Queuing returns the response immediately and lets a worker retry the delivery.
  4. 4. What does Mail::fake() let a test do?

    Mail::fake() records mailables instead of delivering them, and assertSent, assertQueued and assertNothingSent check what the code did.

Summary

  • A mailable is a class describing one email: envelope() for subject and addresses, content() for views, attachments() for files.
  • Send with Mail::to(...)->send(...); queue with queue() or later() so users do not wait.
  • Markdown mail gives a responsive layout and a plain-text twin with a few components.
  • Use MAIL_MAILER=log (or Mailpit) locally and Mail::fake() in tests.
  • Set up SPF, DKIM and DMARC, and use a real mail provider in production.

Next: Notifications