- Introduction
- Configuration
- Writing mailables
- Mail views
- Sending mail
- Attachments
- Tracing and logging
- Writing a transport
- Testing
Introduction
Most applications email their users, such as a confirmation when an order ships or a link that resets a forgotten password. With the mail package, you represent each kind of email as a mailable, a type whose Build method returns the message to send with an email view as its body. You then deliver it through Resend, Amazon SES, or a transport you write yourself.
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 name its own | [email protected], named after APP_NAME |
MAIL_QUEUE_CONNECTION, MAIL_QUEUE |
Where queued email goes | The queue's default connection, and that connection's default queue |
MAIL_LOGO_URL |
The image in the email header | None, so the header shows APP_NAME |
Mailers
A mailer is a named way to send email, such as through Resend or Amazon SES. MAIL_MAILER chooses the mailer that every email goes through unless the code that sends it names another. Laravel includes these mailers:
| Mailer | Description |
|---|---|
resend |
Sends through Resend's API. |
ses |
Sends through Amazon SES. |
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 the info level, and the HTML body at debug, so you can read what your application would have sent.
Sometimes one kind of email should go through a different provider, such as receipts through SES while the rest of your email goes through Resend. To send one email through a mailer other than the default, start with mail.Use and the mailer's name instead of mail.To:
1err := mail.Use("ses").To(customer).Send(r, mails.OrderShipped{Order: order})1err := mail.Use("ses").To(customer).Send(r, mails.OrderShipped{Order: order})
Resend
Resend needs only an API key, 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. The mail/resend package holds both as options that only the resend transport reads. List them in a message's Options:
1import (2 "go.laravel.com/mail"3 "go.laravel.com/mail/resend"4)56welcome := mail.Message{7 Subject: "Welcome to Acme",8 Options: []mail.TransportOption{9 resend.Template{10 ID: "welcome",11 Variables: map[string]any{"CTA_LINK": "https://acme.test/start"},12 },13 },14}1516changelog := mail.Message{17 Subject: "What's new in October",18 View: "mails.changelog",19 Data: "October",20 Options: []mail.TransportOption{resend.Topic{ID: "product-updates"}},21}1import (2 "go.laravel.com/mail"3 "go.laravel.com/mail/resend"4)56welcome := mail.Message{7 Subject: "Welcome to Acme",8 Options: []mail.TransportOption{9 resend.Template{10 ID: "welcome",11 Variables: map[string]any{"CTA_LINK": "https://acme.test/start"},12 },13 },14}1516changelog := mail.Message{17 Subject: "What's new in October",18 View: "mails.changelog",19 Data: "October",20 Options: []mail.TransportOption{resend.Topic{ID: "product-updates"}},21}
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, select the ses mailer and name your region with AWS_DEFAULT_REGION. SES_CONFIGURATION_SET is optional, and 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
The ses mailer reads AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_SESSION_TOKEN. Without them, it finds credentials as an S3 disk does, such as the profile that AWS_PROFILE names, or a server's IAM role on an EC2 instance, an ECS task, or an EKS pod. SES sends only from addresses and domains that you've verified with it.
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, list the mailers it tries, in order, in the configure function of your options in bootstrap/app.go:
1// bootstrap/app.go2func configure(cfg *config.Config, env *config.Env) {3 cfg.Mail.Failover = []string{"ses", "resend"}4}1// bootstrap/app.go2func configure(cfg *config.Config, env *config.Env) {3 cfg.Mail.Failover = []string{"ses", "resend"}4}
Defining your own mailers
When you need another mailer beyond the defaults, such as a second Resend account for marketing email, register it in your options' Register function in bootstrap/app.go, under the name you'll send through. Reading credentials from app.Env() respects .env.testing and laraveltest.Env in tests:
1// bootstrap/app.go2func Options() laravel.Options {3 return laravel.Options{4 Register: func(app *laravel.Registrar) error {5 app.Mailer("marketing", &resend.Transport{6 Key: app.Env().String("RESEND_MARKETING_KEY", ""),7 })89 return nil10 },11 // ...12 }13}1// bootstrap/app.go2func Options() laravel.Options {3 return laravel.Options{4 Register: func(app *laravel.Registrar) error {5 app.Mailer("marketing", &resend.Transport{6 Key: app.Env().String("RESEND_MARKETING_KEY", ""),7 })89 return nil10 },11 // ...12 }13}
You may then send through the mailer by name, as in mail.Use("marketing").To(user).Queue(r, mails.Changelog{}). To add a mailer for a provider that Laravel doesn't include, write a transport of your own.
Writing mailables
A mailable is a type representing one kind of email, typically placed in your application's mails package. Its Build method returns the mail.Message to send. For example, suppose your application has an Order model:
1// mails/order_shipped.go2package mails34import (5 "fmt"67 "go.laravel.com/mail"89 "app/models"10)1112type OrderShipped struct {13 Order models.Order14}1516func (m OrderShipped) Build() mail.Message {17 return mail.Message{18 Subject: fmt.Sprintf("Order #%d has shipped", m.Order.ID),19 View: "mails.order-shipped",20 Data: m,21 }22}1// mails/order_shipped.go2package mails34import (5 "fmt"67 "go.laravel.com/mail"89 "app/models"10)1112type OrderShipped struct {13 Order models.Order14}1516func (m OrderShipped) Build() mail.Message {17 return mail.Message{18 Subject: fmt.Sprintf("Order #%d has shipped", m.Order.ID),19 View: "mails.order-shipped",20 Data: m,21 }22}
View names the email's view, so mails.order-shipped renders resources/views/mails/order-shipped.html. Data is what the view displays. Passing the mailable itself lets the view read each field by its name, as in {{.Order.ID}}.
Laravel renders that view as the email's HTML body, and automatically generates a matching plain text version from it, so mail clients and spam filters receive both formats without you maintaining two templates.
The code that sends the email fills in the mailable's fields, and Laravel calls Build when that code calls Send or Queue. Build takes no ctx, so build URLs in the view instead, where route and url work as in your other views.
A mailable may also name its own recipients and attachments in its message, such as an invoice email that always goes to the user it's about. To, CC, BCC, and ReplyTo take addresses, and Attachments takes attachments:
1type InvoicePaid struct {2 User models.User3 Number int4 PDF []byte5}67func (m InvoicePaid) Build() mail.Message {8 return mail.Message{9 To: []mail.Address{m.User.MailAddress()},10 Subject: fmt.Sprintf("Invoice #%d", m.Number),11 View: "mails.invoice-paid",12 Data: m,13 Attachments: []mail.Attachment{14 mail.AttachData(m.PDF, fmt.Sprintf("Invoice-%d.pdf", m.Number)),15 },16 }17}1type InvoicePaid struct {2 User models.User3 Number int4 PDF []byte5}67func (m InvoicePaid) Build() mail.Message {8 return mail.Message{9 To: []mail.Address{m.User.MailAddress()},10 Subject: fmt.Sprintf("Invoice #%d", m.Number),11 View: "mails.invoice-paid",12 Data: m,13 Attachments: []mail.Attachment{14 mail.AttachData(m.PDF, fmt.Sprintf("Invoice-%d.pdf", m.Number)),15 },16 }17}
The message
mail.Message holds everything about an email, and a mailable sets only the fields its email needs:
| Field | Sets |
|---|---|
From |
The sender, instead of MAIL_FROM_ADDRESS and MAIL_FROM_NAME. |
ReplyTo |
Addresses that replies go to. |
To, CC, BCC |
Recipients, added to the recipients the code that sends names. |
Subject |
The subject. |
View |
The name of the view that renders the HTML body, and a text body generated from the same view. |
Data |
What View and TextView display. |
TextView |
The name of a .txt view that renders the text body, instead of the generated one. |
HTML |
An HTML body you built yourself, such as with a Markdown renderer, for an email without a View. |
Text |
The plain text body, instead of the generated one. With Text and no View, the email has only a text body. |
Attachments |
Files to attach. |
Inline |
Inline images, by content ID. |
Headers |
Custom headers, such as List-Unsubscribe. |
Tags |
Names and values that the provider stores with the email, for filtering and webhooks. |
Options |
Options for one provider, such as a Resend template. |
Because mail.Message is a mailable too, you may send quick one-off emails without defining a type, such as a note to your operations team when a nightly import finishes:
2 Subject: "Import finished",3 Text: "The nightly import finished.",4})2 Subject: "Import finished",3 Text: "The nightly import finished.",4})
Mail views
Mail views are html/template files in resources/views, like your application's other views. Rendering mail::layout wraps your email in Laravel's responsive layout, complete with a header that shows your logo or APP_NAME linked to APP_URL, and a footer. Place your email's body in the layout's content block:
1<!-- resources/views/mails/order-shipped.html -->23{{template "mail::layout" .}}45{{define "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{{template "mail::panel" (render "delivery" .)}}1718{{template "mail::button" (dict19 "Label" "Track your order"20 "URL" (route "orders.show" "order" .Order.ID)21)}}22{{end}}2324{{define "delivery"}}<strong>Estimated delivery</strong><br>{{.Order.ETA}}{{end}}1<!-- resources/views/mails/order-shipped.html -->23{{template "mail::layout" .}}45{{define "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{{template "mail::panel" (render "delivery" .)}}1718{{template "mail::button" (dict19 "Label" "Track your order"20 "URL" (route "orders.show" "order" .Order.ID)21)}}22{{end}}2324{{define "delivery"}}<strong>Estimated delivery</strong><br>{{.Order.ETA}}{{end}}
Email often goes out from a job or a command, so mail views render without a request, even when a handler sends the email. You may still use route, url, and config, and their URLs start with APP_URL. Functions that read the request, such as old, csrfField, and session, fail the render.
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 works well for most applications, and save you from wrestling with email HTML and inline styles. Each component takes one value, so pass a button its settings with dict, and pass a component that wraps content a block of your own with render, as shown above:
| Component | Shows |
|---|---|
{{template "mail::button" (dict "Label" "Pay" "URL" .URL)}} |
A link styled as a button: black, or white with a border when you add "Secondary" true. Add "Align" "center" or "Align" "right" to move it. |
{{template "mail::panel" (render "eta" .)}} |
A box that sets content apart. |
{{template "mail::table" (render "items" .)}} |
A wrapper for an HTML <table>. |
{{template "mail::subcopy" (render "link" .)}} |
Fine print below the body. Put it in the subcopy block. |
{{template "mail::header"}} |
The header row that mail::layout shows. |
{{template "mail::footer" "Acme Inc."}} |
The footer that mail::layout shows. |
render runs one of the view's own {{define}} blocks with the value you pass it, and returns the block's HTML. For example, the block that a table wraps may loop over the order's items:
1{{template "mail::table" (render "items" .)}}23{{define "items"}}4<table>5<tr><th>Item</th><th>Qty</th><th>Amount</th></tr>6{{range .Order.Items}}<tr><td>{{.Name}}</td><td>{{.Qty}}</td><td>{{.Amount}}</td></tr>{{end}}7</table>8{{end}}1{{template "mail::table" (render "items" .)}}23{{define "items"}}4<table>5<tr><th>Item</th><th>Qty</th><th>Amount</th></tr>6{{range .Order.Items}}<tr><td>{{.Name}}</td><td>{{.Qty}}</td><td>{{.Amount}}</td></tr>{{end}}7</table>8{{end}}
mail::layout 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 | {{template "mail::header"}} |
footer |
The footer | © {{config.App.Name}}. All rights reserved. |
head |
Extra tags in <head> |
Empty |
The layout reads your application's name, URL, and logo with config, as in {{config.App.Name}}, and your own mail views may do the same.
Plain text versions
Some people read email as plain text, and spam filters trust an email more when it has a text body. Laravel generates a text body for every email by rendering the view a second time with simplified component markup, and converting that HTML into plain text. The order email above becomes:
1Acme: https://acme.test23Your order shipped4==================56Thanks for shopping with us! We've packed up order #42 and handed it to the carrier.78Use the tracking link below for the latest updates. It may take a few hours for the first scan to appear.910 Estimated delivery11 November 27–301213Track your order: https://acme.test/orders/421415© Acme. All rights reserved.1Acme: https://acme.test23Your order shipped4==================56Thanks for shopping with us! We've packed up order #42 and handed it to the carrier.78Use the tracking link below for the latest updates. It may take a few hours for the first scan to appear.910 Estimated delivery11 November 27–301213Track your order: https://acme.test/orders/421415© Acme. All rights reserved.
During the second render, isText is true, so your own views may leave out markup that has no place in text, as in {{if not isText}}<img src="https://acme.test/images/hero.png" alt="">{{end}}.
If you'd rather write the text body yourself, add a .txt view with the same name, such as resources/views/mails/order-shipped.txt, and set the message's TextView to mails.order-shipped. text/template renders the file and escapes nothing, so & and < show as they are:
1Your order #{{.Order.ID}} shipped, and arrives {{.Order.ETA}}.23Track it at {{route "orders.show" "order" .Order.ID}}1Your order #{{.Order.ID}} shipped, and arrives {{.Order.ETA}}.23Track it at {{route "orders.show" "order" .Order.ID}}
For a text body that needs no view at all, set the message's Text.
Customizing the layout
To give every email the same footer, header, or extra CSS, write your own base view. Render mail::layout and define the blocks you want to change:
1<!-- resources/views/mails/base.html -->23{{template "mail::layout" .}}45{{define "footer"}}{{template "mail::footer" (render "preferences" .)}}{{end}}67{{define "preferences"}}Acme Inc. · <a href="{{url "/settings/email"}}">Email preferences</a>{{end}}89{{define "head"}}<style>.content h1 { font-size: 20px; }</style>{{end}}1<!-- resources/views/mails/base.html -->23{{template "mail::layout" .}}45{{define "footer"}}{{template "mail::footer" (render "preferences" .)}}{{end}}67{{define "preferences"}}Acme Inc. · <a href="{{url "/settings/email"}}">Email preferences</a>{{end}}89{{define "head"}}<style>.content h1 { font-size: 20px; }</style>{{end}}
Then render your base view instead of mail::layout:
1<!-- resources/views/mails/order-shipped.html -->23{{template "mails.base" .}}45{{define "content"}}6<h1>Your order shipped</h1>78{{template "mail::button" (dict9 "Label" "Track your order"10 "URL" (route "orders.show" "order" .Order.ID)11)}}12{{end}}1<!-- resources/views/mails/order-shipped.html -->23{{template "mails.base" .}}45{{define "content"}}6<h1>Your order shipped</h1>78{{template "mail::button" (dict9 "Label" "Track your order"10 "URL" (route "orders.show" "order" .Order.ID)11)}}12{{end}}
To change a block for a single email, define it in that email's view instead. 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 layout itself, copy Laravel's view into resources/views/vendor/mail/ and edit your copy. The vendor:publish command copies one component, such as the button:
1laravel vendor:publish mail button1laravel vendor:publish mail button
Run the command without a component's name to copy every component and the layout. Laravel then renders your copy wherever an email uses that component, including Laravel's own password reset and verification emails, and keeps using its own view for each one you didn't copy:
| Laravel's view | Your copy |
|---|---|
mail::button |
resources/views/vendor/mail/button.html |
mail::layout |
resources/views/vendor/mail/layout.html |
Each component's view has an {{if isText}} branch, which writes the component's markup for the text render, such as the button's label and URL. Keep that branch when you change the component's HTML.
Because html/template strips HTML comments, use {{mso ...}} to emit Outlook conditional comments (<!--[if mso]>...<![endif]-->). mso writes unescaped markup, so pass only literal strings written in the view, never user data.
Previewing mail
While designing an email, you can preview it in your browser without sending it. mail.Render returns the *mail.Email that a transport would receive, so a route that you register only in the local environment may return the email's HTML:
1// handlers/mailpreview/mailpreview.go2package mailpreview34import (5 "go.laravel.com/mail"6 "go.laravel.com/model"7 "go.laravel.com/web"89 "app/mails"10 "app/models"11)1213func OrderShipped(r *web.Request) *web.Response {14 order, err := model.FromRoute[models.Order](r, "order")15 if err != nil {16 return web.Fail(err)17 }1819 email, err := mail.Render(r, mails.OrderShipped{Order: order})20 if err != nil {21 return web.Fail(err)22 }2324 return web.HTML(email.HTML)25}1// handlers/mailpreview/mailpreview.go2package mailpreview34import (5 "go.laravel.com/mail"6 "go.laravel.com/model"7 "go.laravel.com/web"89 "app/mails"10 "app/models"11)1213func OrderShipped(r *web.Request) *web.Response {14 order, err := model.FromRoute[models.Order](r, "order")15 if err != nil {16 return web.Fail(err)17 }1819 email, err := mail.Render(r, mails.OrderShipped{Order: order})20 if err != nil {21 return web.Fail(err)22 }2324 return web.HTML(email.HTML)25}
Sending mail
To send a mailable, name its recipients with mail.To and call Queue or Send. Most handlers should queue email, so the response doesn't wait on the mail provider and a queue worker can retry a failed send. For example, this handler ships an order and emails the customer:
1package orders23import (4 "go.laravel.com/mail"5 "go.laravel.com/model"6 "go.laravel.com/web"78 "app/mails"9 "app/models"10)1112func Ship(r *web.Request) *web.Response {13 order, err := model.FromRoute[models.Order](r, "order")14 if err != nil {15 return web.Fail(err)16 }1718 customer, err := model.Find[models.User](r, order.UserID)19 if err != nil {20 return web.Fail(err)21 }2223 // Ship the order...2425 if err := mail.To(customer).Queue(r, mails.OrderShipped{Order: order}); err != nil {26 return web.Fail(err)27 }2829 return web.RedirectRoute("orders.show", "order", order.ID)30}1package orders23import (4 "go.laravel.com/mail"5 "go.laravel.com/model"6 "go.laravel.com/web"78 "app/mails"9 "app/models"10)1112func Ship(r *web.Request) *web.Response {13 order, err := model.FromRoute[models.Order](r, "order")14 if err != nil {15 return web.Fail(err)16 }1718 customer, err := model.Find[models.User](r, order.UserID)19 if err != nil {20 return web.Fail(err)21 }2223 // Ship the order...2425 if err := mail.To(customer).Queue(r, mails.OrderShipped{Order: order}); err != nil {26 return web.Fail(err)27 }2829 return web.RedirectRoute("orders.show", "order", order.ID)30}
A queued job, a command, or a function deeper in your application sends email as this handler does, but passes the ctx it received instead of r.
Both methods render and check the email before they return, so a view that fails to render, an invalid address, or a missing recipient returns an error at the call site before anything reaches your mail provider:
Queuepushes the rendered email onto your queue, and returns right away while a queue worker delivers it, with retries that survive crashes and deploys.Senddelivers the email straight away and waits for the provider's answer, returning the provider's error when it refuses the email. Laravel doesn't retry a failed send, so useSendin a command, or in a job that retries on its own:
1err := mail.To(customer).Send(ctx, mails.OrderShipped{Order: order})1err := mail.To(customer).Send(ctx, mails.OrderShipped{Order: order})
If a mailable already names its recipients in its message, as InvoicePaid does, you may skip mail.To and pass the mailable straight to mail.Queue or mail.Send:
1err := mail.Queue(r, mails.InvoicePaid{User: user, Number: 42, PDF: pdf})1err := mail.Queue(r, mails.InvoicePaid{User: user, Number: 42, PDF: pdf})
Recipients
To, CC, and BCC take any number of values that have a MailAddress method, such as a mail.Address. Give your User model this method in models/user.go so you may pass a user directly:
1// models/user.go2func (u User) MailAddress() mail.Address {3 return mail.Address{Name: u.Name, Email: u.Email}4}1// models/user.go2func (u User) MailAddress() mail.Address {3 return mail.Address{Name: u.Name, Email: u.Email}4}
Give any other model that receives email a MailAddress method of its own, such as a team that receives its invoices at a billing address. For literal email addresses, use mail.Addr(email, name...), which builds a mail.Address. Each call adds recipients and returns a new mailer, so you may chain the calls, and keep a mailer to send several emails to the same people:
1mail.To(user)3mail.To(6)7mail.To(user).1mail.To(user)3mail.To(6)7mail.To(user).
The signed-in user is a *models.User, which has the same method, so a handler may send straight to them. For example, suppose your application defines a Welcome mailable:
1func ResendWelcome(r *web.Request) *web.Response {2 if err := mail.To(models.CurrentUser(r)).Queue(r, mails.Welcome{}); err != nil {3 return web.Fail(err)4 }56 return web.Text("We've sent the welcome email again.")7}1func ResendWelcome(r *web.Request) *web.Response {2 if err := mail.To(models.CurrentUser(r)).Queue(r, mails.Welcome{}); err != nil {3 return web.Fail(err)4 }56 return web.Text("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. Queued email goes to the connection and queue that MAIL_QUEUE_CONNECTION and MAIL_QUEUE name. Before you call Queue, you may delay the email and choose where its job goes. In the Ship handler above:
1err := mail.To(customer).2 Delay(10*time.Minute).3 OnConnection("redis").4 OnQueue("mail").5 Queue(r, mails.OrderShipped{Order: order})1err := mail.To(customer).2 Delay(10*time.Minute).3 OnConnection("redis").4 OnQueue("mail").5 Queue(r, mails.OrderShipped{Order: order})
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. The worker tries three times, ten seconds and then a minute apart. When the provider rejects the email for good, such as for an address that doesn't exist, the job fails without another try, and laravel queue:failed lists it. Like every job, an email queued with a transaction's ctx waits for the 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:
1// jobs/send_delivery_update.go2package jobs34import (5 "context"67 "go.laravel.com/mail"8 "go.laravel.com/model"910 "app/mails"11 "app/models"12)1314type SendDeliveryUpdate struct {15 OrderID int6416}1718func (j SendDeliveryUpdate) Handle(ctx context.Context) error {19 order, err := model.Find[models.Order](ctx, j.OrderID)20 if err != nil {21 return err22 }2324 customer, err := model.Find[models.User](ctx, order.UserID)25 if err != nil {26 return err27 }2829 return mail.To(customer).Send(ctx, mails.OrderShipped{Order: order})30}1// jobs/send_delivery_update.go2package jobs34import (5 "context"67 "go.laravel.com/mail"8 "go.laravel.com/model"910 "app/mails"11 "app/models"12)1314type SendDeliveryUpdate struct {15 OrderID int6416}1718func (j SendDeliveryUpdate) Handle(ctx context.Context) error {19 order, err := model.Find[models.Order](ctx, j.OrderID)20 if err != nil {21 return err22 }2324 customer, err := model.Find[models.User](ctx, order.UserID)25 if err != nil {26 return err27 }2829 return mail.To(customer).Send(ctx, mails.OrderShipped{Order: order})30}
Sending in the background
If you want to send an email without waiting for your mail provider and without running a queue worker, send it as background work. In the Ship handler above, the handler then returns without waiting for the provider:
1r.Background(func(ctx context.Context) error {2 return mail.To(customer).Send(ctx, mails.OrderShipped{Order: order})3})45return web.RedirectRoute("orders.show", "order", order.ID)1r.Background(func(ctx context.Context) error {2 return mail.To(customer).Send(ctx, mails.OrderShipped{Order: order})3})45return web.RedirectRoute("orders.show", "order", order.ID)
Inside a transaction, the background send starts once the transaction commits, and a rollback discards it. Laravel reports a failed send, and the server waits for background sends to finish when it shuts down. However, background work isn't stored anywhere, so a failed send isn't retried and a crash loses the email. Use Queue for email that must arrive.
Queue automatically waits for an active database transaction to commit before dispatching, whereas Send delivers immediately. If you call Send inside a transaction, wrap it in db.AfterCommit.
Attachments
To attach files to an email, list them in the message's Attachments. For example, this mailable attaches an invoice PDF that your application rendered, along with your terms of service:
1type InvoicePaid struct {2 Number int3 PDF []byte4}56func (m InvoicePaid) Build() mail.Message {7 return mail.Message{8 Subject: fmt.Sprintf("Invoice #%d", m.Number),9 View: "mails.invoice-paid",10 Data: m,11 Attachments: []mail.Attachment{12 mail.AttachData(m.PDF, fmt.Sprintf("Invoice-%d.pdf", m.Number)),13 mail.AttachFile("resources/terms.pdf"),14 },15 }16}1type InvoicePaid struct {2 Number int3 PDF []byte4}56func (m InvoicePaid) Build() mail.Message {7 return mail.Message{8 Subject: fmt.Sprintf("Invoice #%d", m.Number),9 View: "mails.invoice-paid",10 Data: m,11 Attachments: []mail.Attachment{12 mail.AttachData(m.PDF, fmt.Sprintf("Invoice-%d.pdf", m.Number)),13 mail.AttachFile("resources/terms.pdf"),14 },15 }16}
A file may come from memory, from your application's own files, from a storage disk, or from the web. Laravel has a function for each source:
| Function | Attaches |
|---|---|
AttachData(data, |
Bytes you already have in memory, such as a PDF your application generated. |
AttachUpload(upload, |
A file that the visitor uploaded with the current request. |
AttachFile(path) |
A file shipped with your application. A relative path is relative to your application's base path. |
AttachDisk(disk, |
A file on one of your application's storage disks, such as S3, by the disk's name. |
AttachFS(fsys, |
A file in any fs.FS, such as files you embed. |
AttachURL(url) |
A file at an HTTPS URL. Resend fetches it itself, and other transports download it. |
An email's attachments may total up to 25 MiB. You may chain As and WithMime on any attachment to set the file name and content type that the recipient sees. By default, the name is the last part of the path or URL, and the content type follows the name's extension, such as application/pdf for Contract.pdf:
1mail.AttachURL("https://acme.test/guides/onboarding").2 As("Onboarding.pdf").3 WithMime("application/pdf")1mail.AttachURL("https://acme.test/guides/onboarding").2 As("Onboarding.pdf").3 WithMime("application/pdf")
AttachFile, AttachDisk, AttachFS, and AttachURL read the file when the email is sent. A queued email's job stores only where each of those files is, so the file must still exist when the worker sends the email, and Queue returns an error for an attachment from AttachFS, which the job can't store. AttachData and AttachUpload are the exceptions, because the job holds their bytes.
Laravel deletes an uploaded file once the response is sent, so AttachUpload reads the file when you call Send or Queue. It detects the content type from the file's contents, rather than trusting what the visitor's browser claims. For example, this handler emails the user a copy of the signed contract they upload:
1func StoreContract(r *web.Request) *web.Response {2 var form struct {3 Contract *web.Upload `json:"contract"`4 }5 if err := r.BindInto(&form); err != nil {6 return web.Fail(err)7 }8 if form.Contract == nil {9 return web.Invalid("contract", "Choose the signed contract to upload.")10 }1112 err := mail.To(models.CurrentUser(r)).Queue(r, mail.Message{13 Subject: "Your signed contract",14 Text: "Here's a copy of the contract you signed.",15 Attachments: []mail.Attachment{mail.AttachUpload(form.Contract, "Contract.pdf")},16 })17 if err != nil {18 return web.Fail(err)19 }2021 return web.Back()22}1func StoreContract(r *web.Request) *web.Response {2 var form struct {3 Contract *web.Upload `json:"contract"`4 }5 if err := r.BindInto(&form); err != nil {6 return web.Fail(err)7 }8 if form.Contract == nil {9 return web.Invalid("contract", "Choose the signed contract to upload.")10 }1112 err := mail.To(models.CurrentUser(r)).Queue(r, mail.Message{13 Subject: "Your signed contract",14 Text: "Here's a copy of the contract you signed.",15 Attachments: []mail.Attachment{mail.AttachUpload(form.Contract, "Contract.pdf")},16 })17 if err != nil {18 return web.Fail(err)19 }2021 return web.Back()22}
The visitor's browser names the file, so give the attachment a name of your own, such as Contract.pdf, or pass contract.Name to keep the visitor's. The job holds the whole file until a worker sends the email, so for a large file, store the upload on a disk your workers can reach and attach it with AttachDisk instead. Make sure the file stays on the disk until the email and any retries are sent, and 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, put it in the message's Inline under a content ID:
1mail.Message{2 Subject: "Welcome to Acme",3 View: "mails.welcome",4 Inline: map[string]mail.Attachment{"logo": mail.AttachFile("resources/images/logo.png")},5}1mail.Message{2 Subject: "Welcome to Acme",3 View: "mails.welcome",4 Inline: map[string]mail.Attachment{"logo": mail.AttachFile("resources/images/logo.png")},5}
The view then shows the image with a cid: URL and the same content ID:
1<img src="cid:logo" alt="Acme">1<img src="cid:logo" alt="Acme">
Tracing and logging
When your application exports traces, Laravel traces each email in a mail.render span and a mail.send span, inside the span of the request, command, or job that sends it. The spans carry the mailable's type, the mailer, the transport, the email's ID, and how many recipients it has, but never addresses, subjects, or bodies. The Resend and SES mailers use Laravel's HTTP client, so each mail.send span includes a child span for the provider request and the HTTP client fake intercepts those requests in tests. Each successful send also writes a mail sent line at the debug level that names the mailer, the email's ID, and the mailable's type.
Writing a transport
To deliver email through another provider, such as Postmark, write a transport, which is any type with a Send(ctx, *mail.Email) error method. For example, this Postmark transport uses Laravel's HTTP client, so you can test it with the HTTP client fake:
1// mails/postmark.go2package mails34import (5 "context"6 "strings"78 "go.laravel.com/httpclient"9 "go.laravel.com/mail"10)1112type Postmark struct {13 Token string14}1516func (p Postmark) Send(ctx context.Context, email *mail.Email) error {17 var to []string18 for _, address := range email.To {19 to = append(to, address.String())20 }2122 _, err := httpclient.Header("X-Postmark-Server-Token", p.Token).23 JSON(map[string]any{24 "From": email.From.String(),25 "To": strings.Join(to, ","),26 "Subject": email.Subject,27 "HtmlBody": email.HTML,28 "TextBody": email.Text,29 }).30 EnsureSuccessful().31 Post(ctx, "https://api.postmarkapp.com/email")3233 return err34}1// mails/postmark.go2package mails34import (5 "context"6 "strings"78 "go.laravel.com/httpclient"9 "go.laravel.com/mail"10)1112type Postmark struct {13 Token string14}1516func (p Postmark) Send(ctx context.Context, email *mail.Email) error {17 var to []string18 for _, address := range email.To {19 to = append(to, address.String())20 }2122 _, err := httpclient.Header("X-Postmark-Server-Token", p.Token).23 JSON(map[string]any{24 "From": email.From.String(),25 "To": strings.Join(to, ","),26 "Subject": email.Subject,27 "HtmlBody": email.HTML,28 "TextBody": email.Text,29 }).30 EnsureSuccessful().31 Post(ctx, "https://api.postmarkapp.com/email")3233 return err34}
The transport receives an email that Laravel has already rendered and checked. For a provider that takes a raw message, email.MIME(ctx) returns the email in MIME form with its attachments. Return provider errors from Send, so the code that sent the email receives them and queue workers retry failed deliveries. A 4xx response from EnsureSuccessful, other than 408, 409, or 429, fails a queued email immediately without retrying, because repeating the request would receive the same rejection.
Register the transport as a mailer in your options' Register function in bootstrap/app.go, under the name that MAIL_MAILER selects. This example reads the API token from a POSTMARK_TOKEN variable through app.Env():
1// bootstrap/app.go2func Options() laravel.Options {3 return laravel.Options{4 Register: func(app *laravel.Registrar) error {5 app.Mailer("postmark", mails.Postmark{6 Token: app.Env().String("POSTMARK_TOKEN", ""),7 })89 return nil10 },11 // ...12 }13}1// bootstrap/app.go2func Options() laravel.Options {3 return laravel.Options{4 Register: func(app *laravel.Registrar) error {5 app.Mailer("postmark", mails.Postmark{6 Token: app.Env().String("POSTMARK_TOKEN", ""),7 })89 return nil10 },11 // ...12 }13}
Then select the mailer and supply its token in .env:
1MAIL_MAILER=postmark2POSTMARK_TOKEN=pm_1231MAIL_MAILER=postmark2POSTMARK_TOKEN=pm_123
Registering a mailer with the name of one of Laravel's built-in mailers, such as ses, replaces Laravel's mailer. If you're shipping a reusable transport in a package, add the mailer from the package's Register method with app.Mailer("postmark", transport) instead. An application's own mailer with the same name wins.
A custom transport may also define provider-specific options, like Resend's templates and topics. An option is a type whose TransportOption method returns the option's name. A queued email holds its options as JSON, so the option's type must encode to JSON:
1type MessageStream struct {2 ID string `json:"id"`3}45func (MessageStream) TransportOption() string { return "postmark.message_stream" }1type MessageStream struct {2 ID string `json:"id"`3}45func (MessageStream) TransportOption() string { return "postmark.message_stream" }
List the option in a message's Options, then read it inside your transport's Send with the email's Option method, which also reports whether the email has one:
1// When building the message...2mail.Message{3 Subject: "Product updates",4 View: "mails.updates",5 Options: []mail.TransportOption{MessageStream{ID: "broadcast"}},6}78// Inside Postmark's Send...9stream, ok, err := email.Option[MessageStream]()10if err != nil {11 return err12}13if !ok {14 stream.ID = "outbound"15}1// When building the message...2mail.Message{3 Subject: "Product updates",4 View: "mails.updates",5 Options: []mail.TransportOption{MessageStream{ID: "broadcast"}},6}78// Inside Postmark's Send...9stream, ok, err := email.Option[MessageStream]()10if err != nil {11 return err12}13if !ok {14 stream.ID = "outbound"15}
Testing
When you test code that sends email, you want to know which email it sent and to whom, without reaching a provider. mailtest.New gives your test's application a fake mailer that 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, and a view that fails to render fails the test:
1package feature_test23import (4 "strings"5 "testing"67 "go.laravel.com/mail"8 "go.laravel.com/mailtest"910 "app/mails"11 "app/tests"12)1314func TestShippingAnOrderEmailsTheCustomer(t *testing.T) {15 client := tests.New(t)16 emails := mailtest.New(client)1718 // Create the user and order 42...1920 client.Post("/orders/42/ship", nil).AssertRedirect("/orders/42")2122 emails.AssertQueued(func(m mails.OrderShipped, email mail.QueuedEmail) bool {24 })25}1package feature_test23import (4 "strings"5 "testing"67 "go.laravel.com/mail"8 "go.laravel.com/mailtest"910 "app/mails"11 "app/tests"12)1314func TestShippingAnOrderEmailsTheCustomer(t *testing.T) {15 client := tests.New(t)16 emails := mailtest.New(client)1718 // Create the user and order 42...1920 client.Post("/orders/42/ship", nil).AssertRedirect("/orders/42")2122 emails.AssertQueued(func(m mails.OrderShipped, email mail.QueuedEmail) bool {24 })25}
Send counts as sent, and Queue counts as queued. The fake records queued email instead of queueing it, so the test needs no worker. The assertions take the mailable's type, and an optional function that receives the mailable and its email. When you pass the function, Go infers the type from the function's first argument:
| Method | Asserts or returns |
|---|---|
AssertSent[T](match...), AssertQueued[T](match...) |
A mailable of type T was sent, or queued, and matches when you pass match |
AssertSentTimes[T](count), AssertQueuedTimes[T](count) |
Exactly count mailables of type T were sent, or queued |
AssertNotSent[T]() |
No mailable of type T was sent or queued |
AssertNothingSent() |
No email was sent or queued |
Sent[T](), Queued[T]() |
Each sent, or queued, mailable of type T with its email, in order |
Emails(), QueuedEmails() |
Every email that was sent, or queued, in order |
The email passed to the match function has the fields a transport reads, such as Subject, HTML, Text, and Attachments, and its HasTo, HasCC, and HasBCC methods check recipients:
1emails.AssertSent(func(m mails.OrderShipped, email *mail.Email) bool {2 return m.Order.ID == 42 &&5 email.Subject == "Order #42 has shipped" &&6 strings.Contains(email.HTML, "Track your order")7})1emails.AssertSent(func(m mails.OrderShipped, email *mail.Email) bool {2 return m.Order.ID == 42 &&5 email.Subject == "Order #42 has shipped" &&6 strings.Contains(email.HTML, "Track your order")7})
For a queued email, the match function of AssertQueued receives a mail.QueuedEmail, which also holds the Connection, Queue, and Delay the email was queued with. An empty Connection or Queue means the default:
1emails.AssertQueued(func(m mails.OrderShipped, email mail.QueuedEmail) bool {2 return email.Connection == "redis" && email.Queue == "mail" && email.Delay == 10*time.Minute3})1emails.AssertQueued(func(m mails.OrderShipped, email mail.QueuedEmail) bool {2 return email.Connection == "redis" && email.Queue == "mail" && email.Delay == 10*time.Minute3})
To test a mailable on its own without going through a route, render it with mail.Render and inspect the returned email:
1email, err := mail.Render(client.Context(), mails.OrderShipped{Order: order})2if err != nil {3 t.Fatal(err)4}56if !strings.Contains(email.Text, "We've packed up order #42") {7 t.Errorf("text body = %q", email.Text)8}1email, err := mail.Render(client.Context(), mails.OrderShipped{Order: order})2if err != nil {3 t.Fatal(err)4}56if !strings.Contains(email.Text, "We've packed up order #42") {7 t.Errorf("text body = %q", email.Text)8}