- Introduction
- Configuration
- Writing mailables
- Mail views
- Sending mail
- Attachments
- Tracing and logging
- Writing a transport
- Testing
Introduction
Sending transactional email such as order confirmations and password resets should be clean and predictable. With laravel::mail, you represent each type of email as a mailable struct whose fields populate an email view, and deliver it through Resend, Amazon SES, or a custom transport.
Laravel does not bundle an SMTP transport out of the box, though applications and packages may add one by writing a custom transport.
Configuration
The mail configuration names the default mailer, the sender, and the mailers themselves. To get started, set these variables in .env:
| Variable | Sets | Default |
|---|---|---|
MAIL_MAILER |
The default mailer | log |
MAIL_FROM_ADDRESS, MAIL_FROM_NAME |
The sender of every email that doesn't set its own | [email protected], named after APP_NAME |
MAIL_QUEUE_CONNECTION, MAIL_QUEUE |
Where queued email goes | The default queue connection and queue |
MAIL_LOGO_URL |
The image in the email header | None, so the header shows APP_NAME |
Mailers
Each mailer sends email through a transport:
| Transport | Description |
|---|---|
resend |
Sends through Resend's API. |
ses |
Sends through Amazon SES. Requires the ses feature. |
log |
Writes each email to the application log instead of sending. |
failover |
Tries mailers in order until one succeeds when failing over. |
The log mailer is the default, so a new application sends nothing until you choose a provider. Keep it for local development. It logs each email's sender, recipients, subject, and plain-text body at info, and the HTML body at debug, so you can read what your application would have sent.
To send one email through a mailer other than the default, such as the ses mailer, start with mail::mailer instead of mail::to:
1mail::mailer("ses").to(&customer).send(OrderShipped::new(order)?).await?;1mail::mailer("ses").to(&customer).send(OrderShipped::new(order)?).await?;
Resend
Resend needs only an API key and no Cargo feature, so it's the shortest path from the log mailer to real email. Set RESEND_API_KEY to your API key, and select the mailer:
1MAIL_MAILER=resend2RESEND_API_KEY=re_1231MAIL_MAILER=resend2RESEND_API_KEY=re_123
Templates and topics
Resend can store an email's design as a hosted template, and lets recipients unsubscribe by topic. with adds an option that only the resend transport reads:
1use laravel::mail::{Message, resend};2use laravel::view::{data, view};34Message::new()5 .subject("Welcome to Acme")6 .with(7 resend::Template::new("welcome")8 .variable("CTA_LINK", "https://acme.test/start"),9 );1011Message::new()12 .subject("What's new in October")13 .view(view("mail.changelog", data! { month => "October" }))14 .with(resend::Topic::new("product-updates"));1use laravel::mail::{Message, resend};2use laravel::view::{data, view};34Message::new()5 .subject("Welcome to Acme")6 .with(7 resend::Template::new("welcome")8 .variable("CTA_LINK", "https://acme.test/start"),9 );1011Message::new()12 .subject("What's new in October")13 .view(view("mail.changelog", data! { month => "October" }))14 .with(resend::Topic::new("product-updates"));
A Resend template supplies the body, so the first message has no view, html, or text. Other transports ignore Resend's options, so a template email fails on SES, which has no body to send.
Amazon SES
To send through Amazon SES, enable Laravel's ses feature in your Cargo.toml:
1laravel-rust = { version = "0.1", features = ["ses"] }1laravel-rust = { version = "0.1", features = ["ses"] }
The ses mailer reads AWS_DEFAULT_REGION, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_SESSION_TOKEN. Without them, it uses the AWS SDK's defaults, such as a server's IAM role. SES_CONFIGURATION_SET sends every email with that configuration set:
1MAIL_MAILER=ses2AWS_DEFAULT_REGION=us-east-13SES_CONFIGURATION_SET=transactional1MAIL_MAILER=ses2AWS_DEFAULT_REGION=us-east-13SES_CONFIGURATION_SET=transactional
Failing over
When your provider has an outage, a failover mailer sends through a backup. The built-in failover mailer tries resend, then ses, and logs a warning when one fails before moving on to the next. To use it, select it as your default mailer:
1MAIL_MAILER=failover1MAIL_MAILER=failover
To fail over in a different order, or between other mailers, define your own failover mailer:
1mail.add_mailer("failover", MailerConfig::failover(["ses", "resend"]));1mail.add_mailer("failover", MailerConfig::failover(["ses", "resend"]));
Defining your own mailers
When you need another mailer beyond the defaults, such as a second Resend account for marketing email, create a src/config/mail.rs configuration file. Start from Mail::from_env, which already includes the mailers above, and add yours:
1// src/config/mail.rs2use laravel::config::mail::{Mail, Resend};3use laravel::config::{self, Env};45#[config::section]6fn mail(env: &Env) -> Mail {7 let mut mail = Mail::from_env(env);89 mail.add_mailer("marketing", Resend::new(env.require::<String>("RESEND_MARKETING_KEY")));1011 mail12}1// src/config/mail.rs2use laravel::config::mail::{Mail, Resend};3use laravel::config::{self, Env};45#[config::section]6fn mail(env: &Env) -> Mail {7 let mut mail = Mail::from_env(env);89 mail.add_mailer("marketing", Resend::new(env.require::<String>("RESEND_MARKETING_KEY")));1011 mail12}
Then add the file to src/config/mod.rs:
1mod mail;1mod mail;
You may then send through the mailer by name, as in mail::mailer("marketing").
Writing mailables
A mailable is a struct representing one kind of email, typically placed in src/mail.rs. Derive Mailable to expose its fields directly to its email view. For example, suppose your application has an Order model:
1use laravel::mail::Mailable;23#[derive(Mailable)]4#[mail(subject = "Your order has shipped")]5pub struct OrderShipped {6 pub order: Order,7 pub url: String,8}1use laravel::mail::Mailable;23#[derive(Mailable)]4#[mail(subject = "Your order has shipped")]5pub struct OrderShipped {6 pub order: Order,7 pub url: String,8}
The email's view is named after the struct in kebab case, so OrderShipped renders resources/views/mail/order-shipped.html. The view reads each field by its name, as in {{ order.id }}, so each field's type must implement Serialize.
By default, #[derive(Mailable)] renders that view as the email's HTML body and automatically generates a matching plain-text version from it, ensuring mail clients and spam filters receive both formats without you having to maintain two separate templates.
You can customize the subject, HTML view, and plain-text view using options in #[mail(..)]. If you omit subject, Laravel converts the struct name into words (such as "Order Shipped"). Subject strings may also interpolate struct fields using {field} placeholders, and view overrides the default template path:
1#[derive(Mailable)]2#[mail(subject = "Order #{order_id} has shipped", view = "mail.shipped")]3pub struct OrderShipped {4 pub order_id: i64,5 pub url: String,6}1#[derive(Mailable)]2#[mail(subject = "Order #{order_id} has shipped", view = "mail.shipped")]3pub struct OrderShipped {4 pub order_id: i64,5 pub url: String,6}
If you prefer to write a dedicated plain-text template instead of using the generated text body, pass text alongside view (or specify text on its own to send a plain-text-only email):
1#[derive(Mailable)]2#[mail(3 subject = "Your order has shipped",4 view = "mail.shipped",5 text = "mail.shipped-text",6)]7pub struct OrderShipped {8 pub order: Order,9 pub url: String,10}1#[derive(Mailable)]2#[mail(3 subject = "Your order has shipped",4 view = "mail.shipped",5 text = "mail.shipped-text",6)]7pub struct OrderShipped {8 pub order: Order,9 pub url: String,10}
When a mailable needs computed fields (such as a route URL or a formatted total), define a constructor on the struct so callers do not have to build those values every time they send the email. Because you construct the mailable inside your handler or job, the constructor has access to route!, laravel::config(), and the current request context:
1use laravel::prelude::*;23impl OrderShipped {4 pub fn new(order: Order) -> laravel::Result<Self> {5 let url = route!(orders::show, &order)?;67 Ok(Self { order, url })8 }9}1use laravel::prelude::*;23impl OrderShipped {4 pub fn new(order: Order) -> laravel::Result<Self> {5 let url = route!(orders::show, &order)?;67 Ok(Self { order, url })8 }9}
You can also annotate struct fields to set recipients and attachments directly on the mailable. #[mail(to)], #[mail(cc)], #[mail(bcc)], and #[mail(reply_to)] accept any type that converts into recipients while keeping the field available in your template, whereas #[mail(attach)] attaches an Attachment without passing it to the template:
1use laravel::mail::{Attachment, Mailable};23#[derive(Mailable)]4pub struct InvoicePaid {5 #[mail(to)]6 pub user: User,7 pub total: String,8 #[mail(attach)]9 pub pdf: Attachment,10}1use laravel::mail::{Attachment, Mailable};23#[derive(Mailable)]4pub struct InvoicePaid {5 #[mail(to)]6 pub user: User,7 pub total: String,8 #[mail(attach)]9 pub pdf: Attachment,10}
Building the message yourself
For tags, headers, or a message that changes with its data, implement Mailable yourself. Its build method returns the Message to send:
1use laravel::mail::{Mailable, Message};2use laravel::prelude::*;3use laravel::view::{data, view};45pub struct OrderShipped {6 pub order: Order,7}89impl Mailable for OrderShipped {10 fn build(&self) -> laravel::Result<Message> {11 let url = route!(orders::show, &self.order)?;1213 Ok(Message::new()14 .subject(format!("Order #{} has shipped", self.order.id))15 .view(view("mail.order-shipped", data! { order => self.order, url }))16 .tag("category", "shipping"))17 }18}1use laravel::mail::{Mailable, Message};2use laravel::prelude::*;3use laravel::view::{data, view};45pub struct OrderShipped {6 pub order: Order,7}89impl Mailable for OrderShipped {10 fn build(&self) -> laravel::Result<Message> {11 let url = route!(orders::show, &self.order)?;1213 Ok(Message::new()14 .subject(format!("Order #{} has shipped", self.order.id))15 .view(view("mail.order-shipped", data! { order => self.order, url }))16 .tag("category", "shipping"))17 }18}
Message is a builder with these methods:
| Method | Sets |
|---|---|
from |
The sender, instead of MAIL_FROM_ADDRESS. |
reply_to |
Addresses that replies go to. |
to, cc, bcc |
Recipients, added to the recipients the send names. |
subject |
The subject. |
view |
The HTML body, and a text body generated from the same view. |
html, text |
The HTML or plain text body on its own, from a View or a string. |
attach |
An attachment. |
embed |
An inline image. |
header |
A custom header, such as List-Unsubscribe. |
tag |
A name and a value that the provider stores with the email, for filtering and webhooks. |
with |
An option for one provider, such as a Resend template. |
build borrows &self so the mail fake can retain the mailable for assertions in tests. Pass fields by reference (such as .to(&self.user) and .text(&self.summary)), and clone owned values when needed (such as .attach(self.pdf.clone()), since Attachment shares its underlying bytes cheaply).
Because Message itself implements Mailable, you may send quick one-off emails without defining a dedicated struct:
1use laravel::mail::{self, Message};24 .send(Message::new().subject("Import finished").text("The nightly import finished."))5 .await?;1use laravel::mail::{self, Message};24 .send(Message::new().subject("Import finished").text("The nightly import finished."))5 .await?;
Mail views
Mail views are standard views stored in resources/views. Extending laravel::mail.message wraps your email in Laravel's default responsive layout, complete with a branded header (displaying your logo or APP_NAME linked to APP_URL) and footer. Place your email's body inside the content block:
1<!-- resources/views/mail/order-shipped.html -->2{% extends "laravel::mail.message" %}3{% import "laravel::mail.components" as mail %}45{% block content %}6 <h1>Your order shipped</h1>7 <p>8 Thanks for shopping with us! We've packed up order #{{ order.id }} and handed it9 to the carrier.10 </p>11 <p>12 Use the tracking link below for the latest updates. It may take a few hours for13 the first scan to appear.14 </p>1516 {% call mail.panel() %}17 <strong>Estimated delivery</strong><br>18 {{ order.eta }}19 {% endcall %}2021 {{ mail.button("Track your order", url) }}22{% endblock %}1<!-- resources/views/mail/order-shipped.html -->2{% extends "laravel::mail.message" %}3{% import "laravel::mail.components" as mail %}45{% block content %}6 <h1>Your order shipped</h1>7 <p>8 Thanks for shopping with us! We've packed up order #{{ order.id }} and handed it9 to the carrier.10 </p>11 <p>12 Use the tracking link below for the latest updates. It may take a few hours for13 the first scan to appear.14 </p>1516 {% call mail.panel() %}17 <strong>Estimated delivery</strong><br>18 {{ order.eta }}19 {% endcall %}2021 {{ mail.button("Track your order", url) }}22{% endblock %}
Mail views render without the current request, so they don't receive the session, validation errors, or data shared with laravel::view::share.
To show your logo in the header, set MAIL_LOGO_URL to a public URL. Use a PNG 64 pixels tall and at most 400 pixels wide, because Gmail and Outlook don't show SVG images.
Mail components

Laravel's built-in mail components give your emails a clean, modern design that looks great out of the box and works well for most applications, saving you from wrestling with email HTML and inline styles. Import the macro components from laravel::mail.components in each view that uses them, as shown above:
| Component | Shows |
|---|---|
mail.button(label, |
A link styled as a button: black, or white with a border when color is "secondary". align also takes "center" and "right" |
{% call mail.panel() %}..{% endcall %} |
A box that sets content apart |
{% call mail.table() %}..{% endcall %} |
A wrapper for an HTML <table> |
{% call mail.subcopy() %}..{% endcall %} |
Fine print below the body. Put it in the subcopy block |
mail.header(name, |
The header row that laravel::mail.message shows |
{% call mail.footer() %}..{% endcall %} |
The footer row that laravel::mail.message shows |
laravel::mail.message has these blocks:
| Block | Holds | Default |
|---|---|---|
content |
The email's body | Empty |
subcopy |
Fine print, such as the button's URL | Empty |
header |
The header row | mail.header(app_name, app_url, logo=mail_logo) |
footer |
The footer row | © {{ app_name }}. All rights reserved. |
head |
Extra tags in <head> |
Empty |
Every mail view can read app_name, app_url, and mail_logo, from APP_NAME, APP_URL, and MAIL_LOGO_URL.
Plain text versions
Some people read email as plain text, and spam filters trust an email more when it has a text body. view generates a text body for every email by rendering the template with simplified component markup and converting that HTML into plain text. The order email above becomes:
1Acme: https://acme.test23Your order shipped4==================56Order #42 is on its way.78 Arriving Friday910Track your order: https://acme.test/orders/42/track1112© Acme. All rights reserved.1Acme: https://acme.test23Your order shipped4==================56Order #42 is on its way.78 Arriving Friday910Track your order: https://acme.test/orders/42/track1112© Acme. All rights reserved.
During the second render, the mail_text variable is true, so your own views may leave out markup that has no place in text, as in {% if not mail_text %}<img src="..." alt="">{% endif %}. To write the text body yourself, pass a view or a string to text, or set the text option on a derived mailable.
Customizing the layout
To give every email the same footer, header, or extra CSS, write your own base view. Extend laravel::mail.message and override its blocks:
1<!-- resources/views/mail/base.html -->2{% extends "laravel::mail.message" %}3{% import "laravel::mail.components" as mail %}45{% block footer %}6 {% call mail.footer() %}7 Acme Inc. · <a href="{{ url('/settings/email') }}">Email preferences</a>8 {% endcall %}9{% endblock %}1011{% block head %}12 <style>.content h1 { font-size: 20px; }</style>13{% endblock %}1<!-- resources/views/mail/base.html -->2{% extends "laravel::mail.message" %}3{% import "laravel::mail.components" as mail %}45{% block footer %}6 {% call mail.footer() %}7 Acme Inc. · <a href="{{ url('/settings/email') }}">Email preferences</a>8 {% endcall %}9{% endblock %}1011{% block head %}12 <style>.content h1 { font-size: 20px; }</style>13{% endblock %}
Then extend your base view instead of laravel::mail.message:
1<!-- resources/views/mail/order-shipped.html -->2{% extends "mail.base" %}3{% import "laravel::mail.components" as mail %}45{% block content %}6 <h1>Your order shipped</h1>78 {{ mail.button("Track your order", url) }}9{% endblock %}1<!-- resources/views/mail/order-shipped.html -->2{% extends "mail.base" %}3{% import "laravel::mail.components" as mail %}45{% block content %}6 <h1>Your order shipped</h1>78 {{ mail.button("Track your order", url) }}9{% endblock %}
The generated text body uses your blocks too. CSS in the head block may restyle headings, paragraphs, links, lists, and tables. It can't change the components' colors, because some mail clients ignore <style> blocks, so the components set their styles inline. To change those, copy the components.
Customizing the components
To change the components or the frame itself, copy the framework's view from its resources/views/mail/ directory into resources/views/vendor/laravel/mail/, keep the file name, and edit your copy. Laravel uses your copy in place of its own:
| Framework view | Your copy |
|---|---|
laravel::mail.components |
resources/views/vendor/laravel/mail/components.html |
laravel::mail.message |
resources/views/vendor/laravel/mail/message.html |
laravel::mail.layout |
resources/views/vendor/laravel/mail/layout.html |
A copy of components.html replaces every component, so keep the ones you don't change. In a component, {% if mail_text %} chooses the markup of the text render.
Previewing mail
While designing an email, you can preview it directly in your browser without sending it. Structs deriving Mailable implement IntoResponse automatically, so a development route can return a mailable directly:
1use laravel::prelude::*;23pub async fn preview(order: Order) -> laravel::Result<OrderShipped> {4 OrderShipped::new(order)5}1use laravel::prelude::*;23pub async fn preview(order: Order) -> laravel::Result<OrderShipped> {4 OrderShipped::new(order)5}
Message and Email also implement IntoResponse. For a mailable that implements Mailable manually (without #[derive(Mailable)]), pass it to mail::render and return the rendered Email:
1use laravel::mail::{self, Email};2use laravel::prelude::*;34pub async fn preview(order: Order) -> laravel::Result<Email> {5 mail::render(OrderShipped::new(order)?)6}1use laravel::mail::{self, Email};2use laravel::prelude::*;34pub async fn preview(order: Order) -> laravel::Result<Email> {5 mail::render(OrderShipped::new(order)?)6}
Both render the email's HTML body when present, or fall back to its plain-text body for text-only emails.
Sending mail
To send a mailable, specify its recipients with mail::to and call queue, send, or send_background. Most handlers should queue email so HTTP responses don't wait on the mail provider and queue workers can retry transient failures:
1use laravel::mail;2use laravel::prelude::*;34use crate::mail::OrderShipped;5use crate::models::Order;67pub async fn ship(Params(id): Params<i64>) -> laravel::Result<Redirect> {8 let order = Order::query().with(Order::user).find_or_fail(id).await?;910 // Ship the order...1112 mail::to(&order.user).queue(OrderShipped::new(order)?).await?;1314 Ok(Redirect::back())15}1use laravel::mail;2use laravel::prelude::*;34use crate::mail::OrderShipped;5use crate::models::Order;67pub async fn ship(Params(id): Params<i64>) -> laravel::Result<Redirect> {8 let order = Order::query().with(Order::user).find_or_fail(id).await?;910 // Ship the order...1112 mail::to(&order.user).queue(OrderShipped::new(order)?).await?;1314 Ok(Redirect::back())15}
Sending takes ownership of the mailable. To keep using a value after you send it, give the mailable a clone, as in OrderShipped::new(order.clone())?.
All three delivery methods render and validate the email immediately before returning, so template errors or invalid addresses surface at the call site before anything reaches your mail provider:
queuepushes the rendered email onto your queue, returning immediately while queue workers deliver it with automatic retries that survive crashes and deploys.senddelivers the email synchronously and waits for the provider's response, which is useful inside a console command or a background job that already handles retries:
1mail::to(&order.user).send(OrderShipped::new(order)?).await?;1mail::to(&order.user).send(OrderShipped::new(order)?).await?;
send_backgroundspawns an in-process task to deliver the email without waiting on the provider or requiring a queue worker, though it will not retry or survive a restart.
If a mailable already defines its recipient using #[mail(to)], you can skip mail::to altogether and pass the mailable straight to mail::queue, mail::send, or mail::send_background:
1mail::queue(InvoicePaid { user, total, pdf }).await?;1mail::queue(InvoicePaid { user, total, pdf }).await?;
Recipients
to, cc, and bcc accept a &str, a String, an (email, name) pair, an Address, or an array, Vec, or slice of them. To send to your users directly, implement From<&User> for Address once, such as in src/models/user.rs:
1use laravel::mail::Address;23impl From<&User> for Address {4 fn from(user: &User) -> Self {5 Address::new(&user.email).with_name(&user.name)6 }7}1use laravel::mail::Address;23impl From<&User> for Address {4 fn from(user: &User) -> Self {5 Address::new(&user.email).with_name(&user.name)6 }7}
Once implemented, you can pass &User (as well as loaded relationships like &order.user or &team.members, plain email strings, (email, name) pairs, or collections of them) to to, cc, and bcc:
1mail::to(&user);2mail::to(&order.user);1mail::to(&user);2mail::to(&order.user);
The same conversion covers Authenticated<User>, so handlers can send directly to the signed-in user. For example, suppose your application defines a Welcome mailable:
1use laravel::auth::Authenticated;23pub async fn resend_welcome(user: Authenticated<User>) -> laravel::Result<&'static str> {4 mail::to(&user).queue(Welcome).await?;56 Ok("We've sent the welcome email again.")7}1use laravel::auth::Authenticated;23pub async fn resend_welcome(user: Authenticated<User>) -> laravel::Result<&'static str> {4 mail::to(&user).queue(Welcome).await?;56 Ok("We've sent the welcome email again.")7}
Queueing mail
queue sends the email from a queue worker, which retries it when the provider fails. Before you await it, you may delay the email and choose where its job goes. In the ship handler above:
1use laravel::time::ToSpan;23mail::to(&order.user)4 .queue(OrderShipped::new(order)?)5 .delay(10.minutes())6 .on_connection("redis")7 .on_queue("mail")8 .await?;1use laravel::time::ToSpan;23mail::to(&order.user)4 .queue(OrderShipped::new(order)?)5 .delay(10.minutes())6 .on_connection("redis")7 .on_queue("mail")8 .await?;
Laravel renders the email when you queue it, and encrypts it with your application key, so password reset links and other secrets are safe in the queue. Like every job, the email waits for the current database transaction to commit, and a rollback discards it.
The email's content is fixed when you queue it, so a delayed email shows the order as it was then. When an email must show data as of sending, dispatch a job of your own that loads the data and calls send:
1use laravel::mail;2use laravel::queue::{Queueable, job};34#[derive(Queueable)]5pub struct SendDeliveryUpdate {6 pub order_id: i64,7}89#[job]10impl SendDeliveryUpdate {11 async fn handle(self) -> laravel::Result<()> {12 let order = Order::query()13 .with(Order::user)14 .find_or_fail(self.order_id)15 .await?;1617 mail::to(&order.user).send(OrderShipped::new(order)?).await?;1819 Ok(())20 }21}1use laravel::mail;2use laravel::queue::{Queueable, job};34#[derive(Queueable)]5pub struct SendDeliveryUpdate {6 pub order_id: i64,7}89#[job]10impl SendDeliveryUpdate {11 async fn handle(self) -> laravel::Result<()> {12 let order = Order::query()13 .with(Order::user)14 .find_or_fail(self.order_id)15 .await?;1617 mail::to(&order.user).send(OrderShipped::new(order)?).await?;1819 Ok(())20 }21}
Sending in the background
If you want to send an email without waiting for your mail provider and without running a queue worker, call send_background. Unlike send and queue, send_background is synchronous (no .await needed) because it renders the email immediately and hands off delivery to an in-process background task:
1mail::to(&order.user).send_background(OrderShipped::new(order)?)?;1mail::to(&order.user).send_background(OrderShipped::new(order)?)?;
If called inside a database transaction, the background send waits until the transaction commits before delivering the email, and any delivery errors are reported automatically. Because background tasks are not persisted, they are not retried on failure and will not survive a process restart or deploy, so use queue for email that must be delivered reliably.
Attachments
To attach files to a derived mailable, add an Attachment field annotated with #[mail(attach)] (or chain .attach(..) when building a Message manually):
1use laravel::mail::{self, Attachment, Mailable};23#[derive(Mailable)]4#[mail(subject = "Invoice #{number}")]5pub struct InvoicePaid {6 pub number: i64,7 #[mail(attach)]8 pub invoice: Attachment,9 #[mail(attach)]10 pub terms: Attachment,11}1213mail::to(&user)14 .queue(InvoicePaid {15 number,16 invoice: Attachment::from_bytes(pdf, format!("Invoice-{number}.pdf")),17 terms: Attachment::from_path("resources/terms.pdf"),18 })19 .await?;1use laravel::mail::{self, Attachment, Mailable};23#[derive(Mailable)]4#[mail(subject = "Invoice #{number}")]5pub struct InvoicePaid {6 pub number: i64,7 #[mail(attach)]8 pub invoice: Attachment,9 #[mail(attach)]10 pub terms: Attachment,11}1213mail::to(&user)14 .queue(InvoicePaid {15 number,16 invoice: Attachment::from_bytes(pdf, format!("Invoice-{number}.pdf")),17 terms: Attachment::from_path("resources/terms.pdf"),18 })19 .await?;
An email's attachments may total up to 25 MiB. You can chain .name(..) and .content_type(..) on any Attachment to override the filename and MIME type shown to the recipient (by default, the name comes from the path or URL and the MIME type is inferred from the extension).
Attaching files from disk or URLs
Use Attachment::from_path to attach a file shipped with your application (relative to the application base path), or Attachment::from_url to attach a remote file over HTTPS. Both read the file when the email is sent:
1let terms = Attachment::from_path("resources/terms.pdf");23let guide = Attachment::from_url("https://acme.test/guides/onboarding.pdf")4 .name("Onboarding.pdf")5 .content_type("application/pdf");1let terms = Attachment::from_path("resources/terms.pdf");23let guide = Attachment::from_url("https://acme.test/guides/onboarding.pdf")4 .name("Onboarding.pdf")5 .content_type("application/pdf");
Attaching in-memory bytes and uploads
Use Attachment::from_bytes when you already have the file's contents in memory (such as a generated Vec<u8> or String), or Attachment::from_upload to attach an uploaded file, such as the receipt field of a validated form:
1let invoice = Attachment::from_bytes(pdf, format!("Invoice-{number}.pdf"));23let receipt = Attachment::from_upload(&form.receipt).await?;1let invoice = Attachment::from_bytes(pdf, format!("Invoice-{number}.pdf"));23let receipt = Attachment::from_upload(&form.receipt).await?;
Attaching files from storage
Use Attachment::from_storage (for your default storage disk) or Attachment::from_storage_disk to attach a file stored on disk or S3.
Whereas from_bytes and from_upload serialize the full file bytes into a queued email's job payload, storage attachments store only the file path and read the file when the worker sends the email. For queued emails with large files, store the upload on a shared disk first and attach it with from_storage_disk:
1use laravel::auth::Authenticated;2use laravel::http::UploadedFile;3use laravel::mail::{self, Attachment, Mailable};4use laravel::prelude::*;56#[derive(Mailable)]7pub struct ContractReceived {8 #[mail(attach)]9 pub contract: Attachment,10}1112#[laravel::input]13#[validate(authenticated)]14pub struct StoreContract {15 #[validate(required, mimes("pdf"))]16 contract: UploadedFile,17}1819pub async fn store(20 user: Authenticated<User>,21 Valid(form): Valid<StoreContract>,22) -> laravel::Result<Redirect> {23 let path = form.contract.store("mail-attachments").disk("s3").await?;2425 mail::to(&user)26 .queue(ContractReceived {27 contract: Attachment::from_storage_disk("s3", path)28 .name("Contract.pdf"),29 })30 .await?;3132 Ok(Redirect::back())33}1use laravel::auth::Authenticated;2use laravel::http::UploadedFile;3use laravel::mail::{self, Attachment, Mailable};4use laravel::prelude::*;56#[derive(Mailable)]7pub struct ContractReceived {8 #[mail(attach)]9 pub contract: Attachment,10}1112#[laravel::input]13#[validate(authenticated)]14pub struct StoreContract {15 #[validate(required, mimes("pdf"))]16 contract: UploadedFile,17}1819pub async fn store(20 user: Authenticated<User>,21 Valid(form): Valid<StoreContract>,22) -> laravel::Result<Redirect> {23 let path = form.contract.store("mail-attachments").disk("s3").await?;2425 mail::to(&user)26 .queue(ContractReceived {27 contract: Attachment::from_storage_disk("s3", path)28 .name("Contract.pdf"),29 })30 .await?;3132 Ok(Redirect::back())33}
Because store generates a random filename, chain .name(..) so the recipient sees a friendly filename. Make sure the file remains on disk until the email and any retries complete; clean up old attachments with a storage lifecycle rule or a scheduled task.
Inline images
To show an image inside the email, rather than as an attachment, embed it under a content ID. The HTML body, or a mail view, shows it with a cid: URL:
1use laravel::mail::{Attachment, Message};23Message::new()4 .subject("Welcome to Acme")5 .embed("logo", Attachment::from_path("resources/images/logo.png"))6 .html(r#"<img src="cid:logo" alt="Acme"><p>Thanks for signing up.</p>"#)1use laravel::mail::{Attachment, Message};23Message::new()4 .subject("Welcome to Acme")5 .embed("logo", Attachment::from_path("resources/images/logo.png"))6 .html(r#"<img src="cid:logo" alt="Acme"><p>Thanks for signing up.</p>"#)
Tracing and logging
Laravel traces each email in a mail.render span and a mail.send span. The spans carry the mailable's type, the mailer, and IDs, but not addresses, subjects, or bodies. A queued email's job continues the trace of the code that queued it. Each successful send also writes a debug line under the laravel::mail target, as Framework log lines describes.
Writing a transport
To deliver email through another provider, implement the laravel::mail::Transport trait. For example, this Postmark transport uses Laravel's HTTP client so you can test it cleanly with the HTTP fake:
1use laravel::http::client;2use laravel::mail::{Email, SentMessage, Transport};3use serde::Deserialize;4use serde_json::json;56pub struct PostmarkTransport {7 pub token: String,8}910#[derive(Deserialize)]11struct Accepted {12 #[serde(rename = "MessageID")]13 id: String,14}1516impl Transport for PostmarkTransport {17 async fn send(&self, email: &Email) -> laravel::Result<SentMessage> {18 let to: Vec<String> = email.to().iter().map(ToString::to_string).collect();1920 let accepted: Accepted = client::post("https://api.postmarkapp.com/email")21 .header("X-Postmark-Server-Token", &self.token)22 .json(json!({23 "From": email.from().to_string(),24 "To": to.join(","),25 "Subject": email.subject(),26 "HtmlBody": email.html(),27 "TextBody": email.text(),28 }))29 .ensure_successful()30 .await?31 .json()?;3233 Ok(SentMessage::new(accepted.id))34 }35}1use laravel::http::client;2use laravel::mail::{Email, SentMessage, Transport};3use serde::Deserialize;4use serde_json::json;56pub struct PostmarkTransport {7 pub token: String,8}910#[derive(Deserialize)]11struct Accepted {12 #[serde(rename = "MessageID")]13 id: String,14}1516impl Transport for PostmarkTransport {17 async fn send(&self, email: &Email) -> laravel::Result<SentMessage> {18 let to: Vec<String> = email.to().iter().map(ToString::to_string).collect();1920 let accepted: Accepted = client::post("https://api.postmarkapp.com/email")21 .header("X-Postmark-Server-Token", &self.token)22 .json(json!({23 "From": email.from().to_string(),24 "To": to.join(","),25 "Subject": email.subject(),26 "HtmlBody": email.html(),27 "TextBody": email.text(),28 }))29 .ensure_successful()30 .await?31 .json()?;3233 Ok(SentMessage::new(accepted.id))34 }35}
The transport receives an email that Laravel has already rendered and validated. Return provider errors from send so queue workers retry failed deliveries. A 4xx response from ensure_successful, other than 408, 409, or 429, fails the email immediately without retrying because repeating the request would receive the same rejection.
Register the transport driver and add a mailer for it in src/app.rs. The driver factory runs lazily on the mailer's first send (if you are shipping a reusable transport as a crate, register it inside a service provider instead):
1// src/app.rs2use laravel::Application;3use laravel::config::mail::MailerConfig;45pub struct PostmarkConfig {6 pub token: String,7}89Application::configure()10 .with_config(|config, env| {11 config.set(PostmarkConfig {12 token: env.get("POSTMARK_TOKEN").unwrap_or_default(),13 });1415 config16 .mail17 .add_mailer("postmark", MailerConfig::custom("postmark"));18 })19 .with_services(|app| {20 app.mail().extend("postmark", async |app, _mailer| {21 let token = app.config().section::<PostmarkConfig>().token.clone();2223 Ok(PostmarkTransport { token })24 });25 })1// src/app.rs2use laravel::Application;3use laravel::config::mail::MailerConfig;45pub struct PostmarkConfig {6 pub token: String,7}89Application::configure()10 .with_config(|config, env| {11 config.set(PostmarkConfig {12 token: env.get("POSTMARK_TOKEN").unwrap_or_default(),13 });1415 config16 .mail17 .add_mailer("postmark", MailerConfig::custom("postmark"));18 })19 .with_services(|app| {20 app.mail().extend("postmark", async |app, _mailer| {21 let token = app.config().section::<PostmarkConfig>().token.clone();2223 Ok(PostmarkTransport { token })24 });25 })
Then select the mailer and supply its token in .env:
1MAIL_MAILER=postmark2POSTMARK_TOKEN=pm_1231MAIL_MAILER=postmark2POSTMARK_TOKEN=pm_123
A custom transport may also define provider-specific options (like Resend's templates and topics) by implementing TransportOption:
1use laravel::mail::TransportOption;2use serde::{Deserialize, Serialize};34#[derive(Serialize, Deserialize)]5pub struct MessageStream(pub String);67impl TransportOption for MessageStream {8 const NAME: &'static str = "postmark.message_stream";9}1use laravel::mail::TransportOption;2use serde::{Deserialize, Serialize};34#[derive(Serialize, Deserialize)]5pub struct MessageStream(pub String);67impl TransportOption for MessageStream {8 const NAME: &'static str = "postmark.message_stream";9}
Attach the option when building a Message with with, then read it inside your transport's send method using email.option:
1// When building the message...2Message::new()3 .subject("Product updates")4 .view(view("mail.updates", data! {}))5 .with(MessageStream("broadcast".into()));67// Inside PostmarkTransport::send...8let stream = email9 .option::<MessageStream>()?10 .map(|option| option.0)11 .unwrap_or_else(|| "outbound".into());1// When building the message...2Message::new()3 .subject("Product updates")4 .view(view("mail.updates", data! {}))5 .with(MessageStream("broadcast".into()));67// Inside PostmarkTransport::send...8let stream = email9 .option::<MessageStream>()?10 .map(|option| option.0)11 .unwrap_or_else(|| "outbound".into());
Testing
When you test code that sends email, you want to know which email it sent and to whom, without reaching a provider. mail::fake() records email instead of sending it. The fake keeps each mailable with the email it rendered, so your assertions can check the mailable's fields as well as the views. It also reads each file attached with from_path or from_storage, so a template error or a missing attachment fails the test, even for an email you queue:
1use laravel::mail;2use laravel::model::create;3use laravel::testing::prelude::*;45#[laravel::test]6async fn shipping_an_order_emails_the_customer(app: Application) -> laravel::Result<()> {7 let user = create!(User {8 name: "Taylor",10 password: "password",11 })12 .await?;1314 let order = create!(Order { user_id: user.id, total: 2500 }).await?;1516 let mail = mail::fake();1718 app.post(format!("/orders/{}/ship", order.id)).await.assert_redirect();1920 mail.assert_queued_where::<OrderShipped>(|queued| {21 queued.mailable().order.id == order.id23 });2425 Ok(())26}1use laravel::mail;2use laravel::model::create;3use laravel::testing::prelude::*;45#[laravel::test]6async fn shipping_an_order_emails_the_customer(app: Application) -> laravel::Result<()> {7 let user = create!(User {8 name: "Taylor",10 password: "password",11 })12 .await?;1314 let order = create!(Order { user_id: user.id, total: 2500 }).await?;1516 let mail = mail::fake();1718 app.post(format!("/orders/{}/ship", order.id)).await.assert_redirect();1920 mail.assert_queued_where::<OrderShipped>(|queued| {21 queued.mailable().order.id == order.id23 });2425 Ok(())26}
send and send_background count as sent, and queue counts as queued:
| Method | Asserts or returns |
|---|---|
assert_sent::<T>(), assert_queued::<T>() |
A mailable of type T was sent, or queued, at least once |
assert_sent_where::<T>(predicate), assert_queued_where::<T>(predicate) |
A sent, or queued, email of type T matches the predicate |
assert_sent_times::<T>(count), assert_queued_times::<T>(count) |
A mailable of type T was sent, or queued, exactly count times |
assert_not_sent::<T>() |
No mailable of type T was sent or queued |
assert_nothing_sent() |
No email was sent or queued |
sent::<T>(), queued::<T>() |
Each sent, or queued, email of type T with its mailable, in order |
The predicate passed to assert_sent_where or assert_queued_where receives the recorded email, which provides subject(), html(), text(), has_to, has_cc, has_bcc, and mailable() to inspect both the rendered message and the original mailable's fields:
1mail.assert_sent_where::<OrderShipped>(|sent| {4 && sent.subject() == "Your order has shipped"5 && sent.html().is_some_and(|html| html.contains("Track your order"))6 && sent.mailable().order.id == order.id7});1mail.assert_sent_where::<OrderShipped>(|sent| {4 && sent.subject() == "Your order has shipped"5 && sent.html().is_some_and(|html| html.contains("Track your order"))6 && sent.mailable().order.id == order.id7});
For a queued email, the predicate can also verify which queue connection, queue name, and delay were configured via connection(), queue(), and delay():
1mail.assert_queued_where::<OrderShipped>(|queued| {2 queued.connection() == "redis"3 && queued.queue() == "mail"4 && queued.delay() == 10.minutes()5});1mail.assert_queued_where::<OrderShipped>(|queued| {2 queued.connection() == "redis"3 && queued.queue() == "mail"4 && queued.delay() == 10.minutes()5});
To test a mailable on its own without going through a route, render it with mail::render and inspect the returned Email:
1let email = mail::render(OrderShipped::new(order)?)?;23assert_eq!(email.subject(), "Your order has shipped");4assert!(email.text().unwrap().contains("Order #42 is on its way."));1let email = mail::render(OrderShipped::new(order)?)?;23assert_eq!(email.subject(), "Your order has shipped");4assert!(email.text().unwrap().contains("Order #42 is on its way."));