Laravel Reference
Mailables
A Mailable is a class representing one email — its subject, view, and data — kept separate from wherever it gets triggered, whether that's a controller, a queued job, or an Artisan command. This site's own account-lockout email works exactly this way.
php artisan make:mail OrderShipped
class OrderShipped extends Mailable
{
use Queueable, SerializesModels;
public function __construct(
public Order $order,
) {}
public function envelope(): Envelope
{
return new Envelope(subject: 'Your order has shipped');
}
public function content(): Content
{
return new Content(
view: 'emails.orders.shipped',
with: ['order' => $this->order],
);
}
public function attachments(): array
{
return [
Attachment::fromPath(storage_path('invoices/1.pdf')),
Attachment::fromStorageDisk('s3', "invoices/{$this->order->id}.pdf"),
];
}
}
An image referenced directly in the email's view (rather than as an attachment) needs embedding so mail clients display it inline instead of blocking it as a remote image: $message->embed($pathToImage) in the email's Blade template (Laravel makes $message available there), or $message->embedData($rawBytes, 'name.jpg') for data generated on the fly.
Locally, set MAIL_MAILER=log to write every outgoing email to the log file instead of actually sending it, or use a local mail catcher to view sent mail in an inbox-style UI without it ever leaving your machine: Mailpit comes with Laravel Sail, and Herd Pro has its own built-in SMTP mail viewer. Laravel's default mailer is log (set by MAIL_MAILER), so a fresh app writes mail to storage/logs/laravel.log until you configure a real one.
Sending mail
use Illuminate\Support\Facades\Mail;
Mail::to($user)->send(new OrderShipped($order));
Mail::to($user)
->cc($manager)
->bcc('audit@example.com')
->send(new OrderShipped($order));
Queueing mail
Sending mail makes a real network call to your mail provider — queue it so the request/response cycle doesn't wait on that.
class OrderShipped extends Mailable implements ShouldQueue
{
use Queueable, SerializesModels;
// ...
}
// or queue an already-built mailable ad hoc
Mail::to($user)->queue(new OrderShipped($order));
Queued mail only goes out while a worker is running — see the queues guide for workers, retries and failed jobs. If the mail is sent from inside a database transaction, call ->afterCommit() on the mailable so the worker can't pick it up before the data it refers to has been committed. Notifications queue the same way: add implements ShouldQueue (with the Queueable trait) and Laravel queues one job per recipient and channel.
Notifications
Notifications generalise the idea further: one alert, sent down one or more channels (mail, database, Slack, SMS via a package) at once.
php artisan make:notification InvoicePaid
class InvoicePaid extends Notification
{
use Queueable;
public function __construct(
public Invoice $invoice,
) {}
public function via(object $notifiable): array
{
return ['mail', 'database'];
}
public function toMail(object $notifiable): MailMessage
{
return (new MailMessage)
->subject('Invoice Paid')
->line("Invoice #{$this->invoice->id} has been paid.")
->action('View Invoice', route('invoices.show', $this->invoice));
}
public function toArray(object $notifiable): array
{
return ['invoice_id' => $this->invoice->id];
}
}
The route('invoices.show', ...) call above builds a URL from a named route — see the routing guide for how named routes work.
$user->notify(new InvoicePaid($invoice));
// Notify anyone, even without a User model (e.g. a raw email/Slack webhook)
Notification::route('mail', 'ops@example.com')
->notify(new InvoicePaid($invoice));
Notifying an email address without a User model
A notification doesn't need a User. Notification::route() sends it to an address you supply on the spot — useful for an ops mailbox, a contact-form recipient, or a customer who has no account:
use Illuminate\Support\Facades\Notification;
Notification::route('mail', 'ops@example.com')
->notify(new InvoicePaid($invoice));
// With a recipient name
Notification::route('mail', ['ops@example.com' => 'Ops Team'])
->notify(new InvoicePaid($invoice));
// Several channels at once
Notification::route('mail', 'ops@example.com')
->route('slack', '#billing')
->notify(new InvoicePaid($invoice));
Laravel wraps the address in an AnonymousNotifiable and passes it to via(), toMail() and the other methods as $notifiable. That object has no name, email or other model attributes, so don't read them in toMail() — use a generic greeting instead. The database channel is skipped for on-demand notifications (there's no user to attach a row to), so the same ['mail', 'database'] notification works for both users and addresses; only an explicit route('database', ...) throws. A notification that implements ShouldQueue is queued as normal.
To assert it in a test, use assertSentOnDemand() (see testing below).
Building the email with MailMessage
MailMessage is the fluent builder returned from a notification's toMail(). It renders a styled HTML email, plus a plain-text version, from a few chained calls — no view file needed:
public function toMail(object $notifiable): MailMessage
{
return (new MailMessage)
->subject('Invoice Paid')
->greeting('Hello!')
->line("Invoice #{$this->invoice->id} has been paid.")
->lineIf($this->invoice->total > 0, "Amount paid: {$this->invoice->total}")
->action('View Invoice', url("/invoices/{$this->invoice->id}"))
->line('Thank you for using our application!');
}
Each line() becomes a paragraph, action() adds a button, and error() styles the email as a failure (a red button) for things like failed payments. Other useful methods:
(new MailMessage)
->from('billing@example.com', 'Billing')
->replyTo('support@example.com')
->cc('manager@example.com')
->attach(storage_path('invoices/1.pdf'))
->priority(1);
// Use your own template instead of the default layout
(new MailMessage)->markdown('emails.invoice-paid', ['invoice' => $this->invoice]);
(new MailMessage)->view('emails.invoice-paid', ['invoice' => $this->invoice]);
The sender defaults to the from address in config/mail.php (MAIL_FROM_ADDRESS). For a full custom layout, use a Markdown template or a Blade view.
Reading database notifications
// Add the notifications() relation via the Notifiable trait (already on User)
$user->unreadNotifications;
$user->notifications()->latest()->take(10)->get();
$notification->markAsRead();
The database channel needs its own table — generate it once with php artisan make:notifications-table and migrate. Unlike mail, database notifications are cheap to write, which makes them a natural fit for an in-app bell icon or activity feed alongside (or instead of) an email.
Markdown mail
Rather than hand-writing HTML for every Mailable, Laravel ships a set of pre-styled Markdown components — buttons, panels, tables — so a professional-looking email can be written mostly as plain text:
php artisan make:mail OrderShipped --markdown=emails.orders.shipped
The Mailable points its content() at the template with markdown instead of view:
public function content(): Content
{
return new Content(
markdown: 'emails.orders.shipped',
with: ['order' => $this->order, 'trackingUrl' => $this->trackingUrl],
);
}
{{-- resources/views/emails/orders/shipped.blade.php --}}
<x-mail::message>
# Order Shipped
Your order #{{ $order->id }} is on its way.
<x-mail::button :url="$trackingUrl">
Track Order
</x-mail::button>
Thanks,<br>
{{ config('app.name') }}
</x-mail::message>
Because it renders both HTML and plain-text automatically, Markdown mail is usually the better starting point over a plain Blade view unless the design needs something the components can't express. Run php artisan vendor:publish --tag=laravel-mail to copy the underlying templates into the app if the default styling needs changing.
Notification channels beyond mail
The via() method isn't limited to mail and database. Laravel's own packages add channels such as vonage for SMS (laravel/vonage-notification-channel) and slack for Slack messages (laravel/slack-notification-channel), while broadcast is built in and pushes a notification over WebSockets to a listening frontend. Install and configure a package's credentials first; then each channel just needs a matching to{Channel}() method on the notification:
public function via(object $notifiable): array
{
return ['mail', 'slack', 'broadcast'];
}
public function toSlack(object $notifiable): SlackMessage
{
// Illuminate\Notifications\Slack\SlackMessage
return (new SlackMessage)
->text("Invoice #{$this->invoice->id} has been paid.");
}
public function toBroadcast(object $notifiable): BroadcastMessage
{
return new BroadcastMessage(['invoice_id' => $this->invoice->id]);
}
Different notifiable models can also route the same notification differently — a User might prefer Slack while an external contact only has an email address on file — by defining routeNotificationForMail() etc. on the model itself.
toArray() is the fallback for both the database and broadcast channels: each uses its own toDatabase() or toBroadcast() method if you define one, and toArray() otherwise — so define them separately when the two need different shapes (e.g. broadcasting less data to the frontend than gets stored). For a multi-language app, chaining ->locale('fr') onto a notification (or Notification::locale('fr')->send(...)) renders it in a specific locale regardless of the current request's locale, useful for a queued job with no request context to infer it from.
Testing mail and notifications
Mail::fake() and Notification::fake() swap out the real senders in tests, so an assertion can confirm the right thing was sent without actually delivering anything or hitting a real mail provider:
Mail::fake();
// ... code under test that sends mail ...
Mail::assertSent(OrderShipped::class, function ($mail) use ($order) {
return $mail->order->id === $order->id;
});
Notification::fake();
Notification::assertSentTo($user, InvoicePaid::class);
// Notification::route() sends have no user to assert against
Notification::assertSentOnDemand(
InvoicePaid::class,
fn ($notification, array $channels, object $notifiable) => $notifiable->routes['mail'] === 'ops@example.com'
);
// Mail that implements ShouldQueue is queued, not sent
Mail::assertQueued(OrderShipped::class);
These helpers slot into any feature test. Faking is preferable to letting tests send real email even in a local/testing mail driver, since it also verifies the correct Mailable or Notification class was dispatched with the expected data, rather than just that something happened.
Common email delivery problems
- Nothing arrives, and no error. Check
MAIL_MAILER. The default islog, which writes the email tostorage/logs/laravel.loginstead of sending it. Also runphp artisan config:clearif you've changed.envon a server that caches its config. - Queued mail or notifications never send. A
ShouldQueuemailable or notification only runs when a queue worker is processing the queue. With adatabaseorredisconnection, startphp artisan queue:workand check thefailed_jobstable — see the queues guide. - SMTP connection errors. Match the port to the scheme: 587 normally uses STARTTLS, while 465 needs
MAIL_SCHEME=smtps. Mismatches usually show up as timeouts or handshake failures. - Sent, but rejected or in spam. The
MAIL_FROM_ADDRESSdomain needs SPF, DKIM and DMARC records that authorise your mail provider. The SPF checker shows what's published, and the DNS guide covers adding records. Many providers also refuse a From address on a domain you haven't verified. - Email refers to data that isn't there yet. A queued email sent inside a database transaction can run before the commit. Use
afterCommit(), as described in queueing mail above.
Related guides
Mail is usually triggered from somewhere else: an event listener reacting to something happening, a scheduled task sending a digest, or an Artisan command. The queues guide covers keeping it off the request, and the official mail and notifications documentation cover every option.