- Introduction
- Generating Mailables
- Writing Mailables
- Markdown Mailables
- Sending Mail
- Rendering Mailables
- Localizing Mailables
- Testing Mailables
- Mail & Local Development
- Events
Introduction
Sending email doesn't have to be complicated. Laravel provides a clean, simple email API powered by the popular SwiftMailer library. Laravel and SwiftMailer provide drivers for sending email via SMTP, Mailgun, Postmark, Amazon SES, and sendmail
, allowing you to quickly get started sending mail through a local or cloud based service of your choice.
Configuration
Laravel's email services may be configured via your application's config/mail.php
configuration file. Each mailer configured within this file may have its own unique configuration and even its own unique "transport", allowing your application to use different email services to send certain email messages. For example, your application might use Postmark to send transactional emails while using Amazon SES to send bulk emails.
Within your mail
configuration file, you will find a mailers
configuration array. This array contains a sample configuration entry for each of the major mail drivers / transports supported by Laravel, while the default
configuration value determines which mailer will be used by default when your application needs to send an email message.
Driver / Transport Prerequisites
The API based drivers such as Mailgun and Postmark are often simpler and faster than sending mail via SMTP servers. Whenever possible, we recommend that you use one of these drivers. All of the API based drivers require the Guzzle HTTP library, which may be installed via the Composer package manager:
1composer require guzzlehttp/guzzle
1composer require guzzlehttp/guzzle
Mailgun Driver
To use the Mailgun driver, first install the Guzzle HTTP library. Then, set the default
option in your config/mail.php
configuration file to mailgun
. Next, verify that your config/services.php
configuration file contains the following options:
1'mailgun' => [2 'domain' => env('MAILGUN_DOMAIN'),3 'secret' => env('MAILGUN_SECRET'),4],
1'mailgun' => [2 'domain' => env('MAILGUN_DOMAIN'),3 'secret' => env('MAILGUN_SECRET'),4],
If you are not using the United States Mailgun region, you may define your region's endpoint in the services
configuration file:
1'mailgun' => [2 'domain' => env('MAILGUN_DOMAIN'),3 'secret' => env('MAILGUN_SECRET'),4 'endpoint' => env('MAILGUN_ENDPOINT', 'api.eu.mailgun.net'),5],
1'mailgun' => [2 'domain' => env('MAILGUN_DOMAIN'),3 'secret' => env('MAILGUN_SECRET'),4 'endpoint' => env('MAILGUN_ENDPOINT', 'api.eu.mailgun.net'),5],
Postmark Driver
To use the Postmark driver, install Postmark's SwiftMailer transport via Composer:
1composer require wildbit/swiftmailer-postmark
1composer require wildbit/swiftmailer-postmark
Next, install the Guzzle HTTP library and set the default
option in your config/mail.php
configuration file to postmark
. Finally, verify that your config/services.php
configuration file contains the following options:
1'postmark' => [2 'token' => env('POSTMARK_TOKEN'),3],
1'postmark' => [2 'token' => env('POSTMARK_TOKEN'),3],
If you would like to specify the Postmark message stream that should be used by a given mailer, you may add the message_stream_id
configuration option to the mailer's configuration array. This configuration array can be found in your application's config/mail.php
configuration file:
1'postmark' => [2 'transport' => 'postmark',3 'message_stream_id' => env('POSTMARK_MESSAGE_STREAM_ID'),4],
1'postmark' => [2 'transport' => 'postmark',3 'message_stream_id' => env('POSTMARK_MESSAGE_STREAM_ID'),4],
This way you are also able to set up multiple Postmark mailers with different message streams.
SES Driver
To use the Amazon SES driver you must first install the Amazon AWS SDK for PHP. You may install this library via the Composer package manager:
1composer require aws/aws-sdk-php
1composer require aws/aws-sdk-php
Next, set the default
option in your config/mail.php
configuration file to ses
and verify that your config/services.php
configuration file contains the following options:
1'ses' => [2 'key' => env('AWS_ACCESS_KEY_ID'),3 'secret' => env('AWS_SECRET_ACCESS_KEY'),4 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),5],
1'ses' => [2 'key' => env('AWS_ACCESS_KEY_ID'),3 'secret' => env('AWS_SECRET_ACCESS_KEY'),4 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),5],
To utilize AWS temporary credentials via a session token, you may add a token
key to your application's SES configuration:
1'ses' => [2 'key' => env('AWS_ACCESS_KEY_ID'),3 'secret' => env('AWS_SECRET_ACCESS_KEY'),4 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),5 'token' => env('AWS_SESSION_TOKEN'),6],
1'ses' => [2 'key' => env('AWS_ACCESS_KEY_ID'),3 'secret' => env('AWS_SECRET_ACCESS_KEY'),4 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),5 'token' => env('AWS_SESSION_TOKEN'),6],
If you would like to define additional options that Laravel should pass to the AWS SDK's SendRawEmail
method when sending an email, you may define an options
array within your ses
configuration:
1'ses' => [2 'key' => env('AWS_ACCESS_KEY_ID'),3 'secret' => env('AWS_SECRET_ACCESS_KEY'),4 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),5 'options' => [6 'ConfigurationSetName' => 'MyConfigurationSet',7 'Tags' => [8 ['Name' => 'foo', 'Value' => 'bar'],9 ],10 ],11],
1'ses' => [2 'key' => env('AWS_ACCESS_KEY_ID'),3 'secret' => env('AWS_SECRET_ACCESS_KEY'),4 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),5 'options' => [6 'ConfigurationSetName' => 'MyConfigurationSet',7 'Tags' => [8 ['Name' => 'foo', 'Value' => 'bar'],9 ],10 ],11],
Failover Configuration
Sometimes, an external service you have configured to send your application's mail may be down. In these cases, it can be useful to define one or more backup mail delivery configurations that will be used in case your primary delivery driver is down.
To accomplish this, you should define a mailer within your application's mail
configuration file that uses the failover
transport. The configuration array for your application's failover
mailer should contain an array of mailers
that reference the order in which mail drivers should be chosen for delivery:
1'mailers' => [2 'failover' => [3 'transport' => 'failover',4 'mailers' => [5 'postmark',6 'mailgun',7 'sendmail',8 ],9 ],1011 // ...12],
1'mailers' => [2 'failover' => [3 'transport' => 'failover',4 'mailers' => [5 'postmark',6 'mailgun',7 'sendmail',8 ],9 ],1011 // ...12],
Once your failover mailer has been defined, you should set this mailer as the default mailer used by your application by specifying its name as the value of the default
configuration key within your application's mail
configuration file:
1'default' => env('MAIL_MAILER', 'failover'),
1'default' => env('MAIL_MAILER', 'failover'),
Generating Mailables
When building Laravel applications, each type of email sent by your application is represented as a "mailable" class. These classes are stored in the app/Mail
directory. Don't worry if you don't see this directory in your application, since it will be generated for you when you create your first mailable class using the make:mail
Artisan command:
1php artisan make:mail OrderShipped
1php artisan make:mail OrderShipped
Writing Mailables
Once you have generated a mailable class, open it up so we can explore its contents. First, note that all of a mailable class' configuration is done in the build
method. Within this method, you may call various methods such as from
, subject
, view
, and attach
to configure the email's presentation and delivery.
You may type-hint dependencies on the mailable's build
method. The Laravel service container automatically injects these dependencies.
Configuring The Sender
Using The from
Method
First, let's explore configuring the sender of the email. Or, in other words, who the email is going to be "from". There are two ways to configure the sender. First, you may use the from
method within your mailable class' build
method:
1/**2 * Build the message.3 *4 * @return $this5 */6public function build()7{9 ->view('emails.orders.shipped');10}
1/**2 * Build the message.3 *4 * @return $this5 */6public function build()7{9 ->view('emails.orders.shipped');10}
Using A Global from
Address
However, if your application uses the same "from" address for all of its emails, it can become cumbersome to call the from
method in each mailable class you generate. Instead, you may specify a global "from" address in your config/mail.php
configuration file. This address will be used if no other "from" address is specified within the mailable class:
In addition, you may define a global "reply_to" address within your config/mail.php
configuration file:
Configuring The View
Within a mailable class' build
method, you may use the view
method to specify which template should be used when rendering the email's contents. Since each email typically uses a Blade template to render its contents, you have the full power and convenience of the Blade templating engine when building your email's HTML:
1/**2 * Build the message.3 *4 * @return $this5 */6public function build()7{8 return $this->view('emails.orders.shipped');9}
1/**2 * Build the message.3 *4 * @return $this5 */6public function build()7{8 return $this->view('emails.orders.shipped');9}
You may wish to create a resources/views/emails
directory to house all of your email templates; however, you are free to place them wherever you wish within your resources/views
directory.
Plain Text Emails
If you would like to define a plain-text version of your email, you may use the text
method. Like the view
method, the text
method accepts a template name which will be used to render the contents of the email. You are free to define both an HTML and plain-text version of your message:
1/**2 * Build the message.3 *4 * @return $this5 */6public function build()7{8 return $this->view('emails.orders.shipped')9 ->text('emails.orders.shipped_plain');10}
1/**2 * Build the message.3 *4 * @return $this5 */6public function build()7{8 return $this->view('emails.orders.shipped')9 ->text('emails.orders.shipped_plain');10}
View Data
Via Public Properties
Typically, you will want to pass some data to your view that you can utilize when rendering the email's HTML. There are two ways you may make data available to your view. First, any public property defined on your mailable class will automatically be made available to the view. So, for example, you may pass data into your mailable class' constructor and set that data to public properties defined on the class:
1<?php23namespace App\Mail;45use App\Models\Order;6use Illuminate\Bus\Queueable;7use Illuminate\Mail\Mailable;8use Illuminate\Queue\SerializesModels;910class OrderShipped extends Mailable11{12 use Queueable, SerializesModels;1314 /**15 * The order instance.16 *17 * @var \App\Models\Order18 */19 public $order;2021 /**22 * Create a new message instance.23 *24 * @param \App\Models\Order $order25 * @return void26 */27 public function __construct(Order $order)28 {29 $this->order = $order;30 }3132 /**33 * Build the message.34 *35 * @return $this36 */37 public function build()38 {39 return $this->view('emails.orders.shipped');40 }41}
1<?php23namespace App\Mail;45use App\Models\Order;6use Illuminate\Bus\Queueable;7use Illuminate\Mail\Mailable;8use Illuminate\Queue\SerializesModels;910class OrderShipped extends Mailable11{12 use Queueable, SerializesModels;1314 /**15 * The order instance.16 *17 * @var \App\Models\Order18 */19 public $order;2021 /**22 * Create a new message instance.23 *24 * @param \App\Models\Order $order25 * @return void26 */27 public function __construct(Order $order)28 {29 $this->order = $order;30 }3132 /**33 * Build the message.34 *35 * @return $this36 */37 public function build()38 {39 return $this->view('emails.orders.shipped');40 }41}
Once the data has been set to a public property, it will automatically be available in your view, so you may access it like you would access any other data in your Blade templates:
1<div>2 Price: {{ $order->price }}3</div>
1<div>2 Price: {{ $order->price }}3</div>
Via The with
Method:
If you would like to customize the format of your email's data before it is sent to the template, you may manually pass your data to the view via the with
method. Typically, you will still pass data via the mailable class' constructor; however, you should set this data to protected
or private
properties so the data is not automatically made available to the template. Then, when calling the with
method, pass an array of data that you wish to make available to the template:
1<?php23namespace App\Mail;45use App\Models\Order;6use Illuminate\Bus\Queueable;7use Illuminate\Mail\Mailable;8use Illuminate\Queue\SerializesModels;910class OrderShipped extends Mailable11{12 use Queueable, SerializesModels;1314 /**15 * The order instance.16 *17 * @var \App\Models\Order18 */19 protected $order;2021 /**22 * Create a new message instance.23 *24 * @param \App\Models\Order $order25 * @return void26 */27 public function __construct(Order $order)28 {29 $this->order = $order;30 }3132 /**33 * Build the message.34 *35 * @return $this36 */37 public function build()38 {39 return $this->view('emails.orders.shipped')40 ->with([41 'orderName' => $this->order->name,42 'orderPrice' => $this->order->price,43 ]);44 }45}
1<?php23namespace App\Mail;45use App\Models\Order;6use Illuminate\Bus\Queueable;7use Illuminate\Mail\Mailable;8use Illuminate\Queue\SerializesModels;910class OrderShipped extends Mailable11{12 use Queueable, SerializesModels;1314 /**15 * The order instance.16 *17 * @var \App\Models\Order18 */19 protected $order;2021 /**22 * Create a new message instance.23 *24 * @param \App\Models\Order $order25 * @return void26 */27 public function __construct(Order $order)28 {29 $this->order = $order;30 }3132 /**33 * Build the message.34 *35 * @return $this36 */37 public function build()38 {39 return $this->view('emails.orders.shipped')40 ->with([41 'orderName' => $this->order->name,42 'orderPrice' => $this->order->price,43 ]);44 }45}
Once the data has been passed to the with
method, it will automatically be available in your view, so you may access it like you would access any other data in your Blade templates:
1<div>2 Price: {{ $orderPrice }}3</div>
1<div>2 Price: {{ $orderPrice }}3</div>
Attachments
To add attachments to an email, use the attach
method within the mailable class' build
method. The attach
method accepts the full path to the file as its first argument:
1/**2 * Build the message.3 *4 * @return $this5 */6public function build()7{8 return $this->view('emails.orders.shipped')9 ->attach('/path/to/file');10}
1/**2 * Build the message.3 *4 * @return $this5 */6public function build()7{8 return $this->view('emails.orders.shipped')9 ->attach('/path/to/file');10}
When attaching files to a message, you may also specify the display name and / or MIME type by passing an array
as the second argument to the attach
method:
1/**2 * Build the message.3 *4 * @return $this5 */6public function build()7{8 return $this->view('emails.orders.shipped')9 ->attach('/path/to/file', [10 'as' => 'name.pdf',11 'mime' => 'application/pdf',12 ]);13}
1/**2 * Build the message.3 *4 * @return $this5 */6public function build()7{8 return $this->view('emails.orders.shipped')9 ->attach('/path/to/file', [10 'as' => 'name.pdf',11 'mime' => 'application/pdf',12 ]);13}
Attaching Files From Disk
If you have stored a file on one of your filesystem disks, you may attach it to the email using the attachFromStorage
method:
1/**2 * Build the message.3 *4 * @return $this5 */6public function build()7{8 return $this->view('emails.orders.shipped')9 ->attachFromStorage('/path/to/file');10}
1/**2 * Build the message.3 *4 * @return $this5 */6public function build()7{8 return $this->view('emails.orders.shipped')9 ->attachFromStorage('/path/to/file');10}
If necessary, you may specify the file's attachment name and additional options using the second and third arguments to the attachFromStorage
method:
1/**2 * Build the message.3 *4 * @return $this5 */6public function build()7{8 return $this->view('emails.orders.shipped')9 ->attachFromStorage('/path/to/file', 'name.pdf', [10 'mime' => 'application/pdf'11 ]);12}
1/**2 * Build the message.3 *4 * @return $this5 */6public function build()7{8 return $this->view('emails.orders.shipped')9 ->attachFromStorage('/path/to/file', 'name.pdf', [10 'mime' => 'application/pdf'11 ]);12}
The attachFromStorageDisk
method may be used if you need to specify a storage disk other than your default disk:
1/**2 * Build the message.3 *4 * @return $this5 */6public function build()7{8 return $this->view('emails.orders.shipped')9 ->attachFromStorageDisk('s3', '/path/to/file');10}
1/**2 * Build the message.3 *4 * @return $this5 */6public function build()7{8 return $this->view('emails.orders.shipped')9 ->attachFromStorageDisk('s3', '/path/to/file');10}
Raw Data Attachments
The attachData
method may be used to attach a raw string of bytes as an attachment. For example, you might use this method if you have generated a PDF in memory and want to attach it to the email without writing it to disk. The attachData
method accepts the raw data bytes as its first argument, the name of the file as its second argument, and an array of options as its third argument:
1/**2 * Build the message.3 *4 * @return $this5 */6public function build()7{8 return $this->view('emails.orders.shipped')9 ->attachData($this->pdf, 'name.pdf', [10 'mime' => 'application/pdf',11 ]);12}
1/**2 * Build the message.3 *4 * @return $this5 */6public function build()7{8 return $this->view('emails.orders.shipped')9 ->attachData($this->pdf, 'name.pdf', [10 'mime' => 'application/pdf',11 ]);12}
Inline Attachments
Embedding inline images into your emails is typically cumbersome; however, Laravel provides a convenient way to attach images to your emails. To embed an inline image, use the embed
method on the $message
variable within your email template. Laravel automatically makes the $message
variable available to all of your email templates, so you don't need to worry about passing it in manually:
1<body>2 Here is an image:34 <img src="{{ $message->embed($pathToImage) }}">5</body>
1<body>2 Here is an image:34 <img src="{{ $message->embed($pathToImage) }}">5</body>
The $message
variable is not available in plain-text message templates since plain-text messages do not utilize inline attachments.
Embedding Raw Data Attachments
If you already have a raw image data string you wish to embed into an email template, you may call the embedData
method on the $message
variable. When calling the embedData
method, you will need to provide a filename that should be assigned to the embedded image:
1<body>2 Here is an image from raw data:34 <img src="{{ $message->embedData($data, 'example-image.jpg') }}">5</body>
1<body>2 Here is an image from raw data:34 <img src="{{ $message->embedData($data, 'example-image.jpg') }}">5</body>
Customizing The SwiftMailer Message
The withSwiftMessage
method of the Mailable
base class allows you to register a closure which will be invoked with the SwiftMailer message instance before sending the message. This gives you an opportunity to deeply customize the message before it is delivered:
1/**2 * Build the message.3 *4 * @return $this5 */6public function build()7{8 $this->view('emails.orders.shipped');910 $this->withSwiftMessage(function ($message) {11 $message->getHeaders()->addTextHeader(12 'Custom-Header', 'Header Value'13 );14 });1516 return $this;17}
1/**2 * Build the message.3 *4 * @return $this5 */6public function build()7{8 $this->view('emails.orders.shipped');910 $this->withSwiftMessage(function ($message) {11 $message->getHeaders()->addTextHeader(12 'Custom-Header', 'Header Value'13 );14 });1516 return $this;17}
Markdown Mailables
Markdown mailable messages allow you to take advantage of the pre-built templates and components of mail notifications in your mailables. Since the messages are written in Markdown, Laravel is able to render beautiful, responsive HTML templates for the messages while also automatically generating a plain-text counterpart.
Generating Markdown Mailables
To generate a mailable with a corresponding Markdown template, you may use the --markdown
option of the make:mail
Artisan command:
1php artisan make:mail OrderShipped --markdown=emails.orders.shipped
1php artisan make:mail OrderShipped --markdown=emails.orders.shipped
Then, when configuring the mailable within its build
method, call the markdown
method instead of the view
method. The markdown
method accepts the name of the Markdown template and an optional array of data to make available to the template:
1/**2 * Build the message.3 *4 * @return $this5 */6public function build()7{9 ->markdown('emails.orders.shipped', [10 'url' => $this->orderUrl,11 ]);12}
1/**2 * Build the message.3 *4 * @return $this5 */6public function build()7{9 ->markdown('emails.orders.shipped', [10 'url' => $this->orderUrl,11 ]);12}
Writing Markdown Messages
Markdown mailables use a combination of Blade components and Markdown syntax which allow you to easily construct mail messages while leveraging Laravel's pre-built email UI components:
1@component('mail::message')2# Order Shipped34Your order has been shipped!56@component('mail::button', ['url' => $url])7View Order8@endcomponent910Thanks,<br>11{{ config('app.name') }}12@endcomponent
1@component('mail::message')2# Order Shipped34Your order has been shipped!56@component('mail::button', ['url' => $url])7View Order8@endcomponent910Thanks,<br>11{{ config('app.name') }}12@endcomponent
Do not use excess indentation when writing Markdown emails. Per Markdown standards, Markdown parsers will render indented content as code blocks.
Button Component
The button component renders a centered button link. The component accepts two arguments, a url
and an optional color
. Supported colors are primary
, success
, and error
. You may add as many button components to a message as you wish:
1@component('mail::button', ['url' => $url, 'color' => 'success'])2View Order3@endcomponent
1@component('mail::button', ['url' => $url, 'color' => 'success'])2View Order3@endcomponent
Panel Component
The panel component renders the given block of text in a panel that has a slightly different background color than the rest of the message. This allows you to draw attention to a given block of text:
1@component('mail::panel')2This is the panel content.3@endcomponent
1@component('mail::panel')2This is the panel content.3@endcomponent
Table Component
The table component allows you to transform a Markdown table into an HTML table. The component accepts the Markdown table as its content. Table column alignment is supported using the default Markdown table alignment syntax:
1@component('mail::table')2| Laravel | Table | Example |3| ------------- |:-------------:| --------:|4| Col 2 is | Centered | $10 |5| Col 3 is | Right-Aligned | $20 |6@endcomponent
1@component('mail::table')2| Laravel | Table | Example |3| ------------- |:-------------:| --------:|4| Col 2 is | Centered | $10 |5| Col 3 is | Right-Aligned | $20 |6@endcomponent
Customizing The Components
You may export all of the Markdown mail components to your own application for customization. To export the components, use the vendor:publish
Artisan command to publish the laravel-mail
asset tag:
1php artisan vendor:publish --tag=laravel-mail
1php artisan vendor:publish --tag=laravel-mail
This command will publish the Markdown mail components to the resources/views/vendor/mail
directory. The mail
directory will contain an html
and a text
directory, each containing their respective representations of every available component. You are free to customize these components however you like.
Customizing The CSS
After exporting the components, the resources/views/vendor/mail/html/themes
directory will contain a default.css
file. You may customize the CSS in this file and your styles will automatically be converted to inline CSS styles within the HTML representations of your Markdown mail messages.
If you would like to build an entirely new theme for Laravel's Markdown components, you may place a CSS file within the html/themes
directory. After naming and saving your CSS file, update the theme
option of your application's config/mail.php
configuration file to match the name of your new theme.
To customize the theme for an individual mailable, you may set the $theme
property of the mailable class to the name of the theme that should be used when sending that mailable.
Sending Mail
To send a message, use the to
method on the Mail
facade. The to
method accepts an email address, a user instance, or a collection of users. If you pass an object or collection of objects, the mailer will automatically use their email
and name
properties when determining the email's recipients, so make sure these attributes are available on your objects. Once you have specified your recipients, you may pass an instance of your mailable class to the send
method:
1<?php23namespace App\Http\Controllers;45use App\Http\Controllers\Controller;6use App\Mail\OrderShipped;7use App\Models\Order;8use Illuminate\Http\Request;9use Illuminate\Support\Facades\Mail;1011class OrderShipmentController extends Controller12{13 /**14 * Ship the given order.15 *16 * @param \Illuminate\Http\Request $request17 * @return \Illuminate\Http\Response18 */19 public function store(Request $request)20 {21 $order = Order::findOrFail($request->order_id);2223 // Ship the order...2425 Mail::to($request->user())->send(new OrderShipped($order));26 }27}
1<?php23namespace App\Http\Controllers;45use App\Http\Controllers\Controller;6use App\Mail\OrderShipped;7use App\Models\Order;8use Illuminate\Http\Request;9use Illuminate\Support\Facades\Mail;1011class OrderShipmentController extends Controller12{13 /**14 * Ship the given order.15 *16 * @param \Illuminate\Http\Request $request17 * @return \Illuminate\Http\Response18 */19 public function store(Request $request)20 {21 $order = Order::findOrFail($request->order_id);2223 // Ship the order...2425 Mail::to($request->user())->send(new OrderShipped($order));26 }27}
You are not limited to just specifying the "to" recipients when sending a message. You are free to set "to", "cc", and "bcc" recipients by chaining their respective methods together:
1Mail::to($request->user())2 ->cc($moreUsers)3 ->bcc($evenMoreUsers)4 ->send(new OrderShipped($order));
1Mail::to($request->user())2 ->cc($moreUsers)3 ->bcc($evenMoreUsers)4 ->send(new OrderShipped($order));
Looping Over Recipients
Occasionally, you may need to send a mailable to a list of recipients by iterating over an array of recipients / email addresses. However, since the to
method appends email addresses to the mailable's list of recipients, each iteration through the loop will send another email to every previous recipient. Therefore, you should always re-create the mailable instance for each recipient:
2 Mail::to($recipient)->send(new OrderShipped($order));3}
2 Mail::to($recipient)->send(new OrderShipped($order));3}
Sending Mail Via A Specific Mailer
By default, Laravel will send email using the mailer configured as the default
mailer in your application's mail
configuration file. However, you may use the mailer
method to send a message using a specific mailer configuration:
1Mail::mailer('postmark')2 ->to($request->user())3 ->send(new OrderShipped($order));
1Mail::mailer('postmark')2 ->to($request->user())3 ->send(new OrderShipped($order));
Queueing Mail
Queueing A Mail Message
Since sending email messages can negatively impact the response time of your application, many developers choose to queue email messages for background sending. Laravel makes this easy using its built-in unified queue API. To queue a mail message, use the queue
method on the Mail
facade after specifying the message's recipients:
1Mail::to($request->user())2 ->cc($moreUsers)3 ->bcc($evenMoreUsers)4 ->queue(new OrderShipped($order));
1Mail::to($request->user())2 ->cc($moreUsers)3 ->bcc($evenMoreUsers)4 ->queue(new OrderShipped($order));
This method will automatically take care of pushing a job onto the queue so the message is sent in the background. You will need to configure your queues before using this feature.
Delayed Message Queueing
If you wish to delay the delivery of a queued email message, you may use the later
method. As its first argument, the later
method accepts a DateTime
instance indicating when the message should be sent:
1Mail::to($request->user())2 ->cc($moreUsers)3 ->bcc($evenMoreUsers)4 ->later(now()->addMinutes(10), new OrderShipped($order));
1Mail::to($request->user())2 ->cc($moreUsers)3 ->bcc($evenMoreUsers)4 ->later(now()->addMinutes(10), new OrderShipped($order));
Pushing To Specific Queues
Since all mailable classes generated using the make:mail
command make use of the Illuminate\Bus\Queueable
trait, you may call the onQueue
and onConnection
methods on any mailable class instance, allowing you to specify the connection and queue name for the message:
1$message = (new OrderShipped($order))2 ->onConnection('sqs')3 ->onQueue('emails');45Mail::to($request->user())6 ->cc($moreUsers)7 ->bcc($evenMoreUsers)8 ->queue($message);
1$message = (new OrderShipped($order))2 ->onConnection('sqs')3 ->onQueue('emails');45Mail::to($request->user())6 ->cc($moreUsers)7 ->bcc($evenMoreUsers)8 ->queue($message);
Queueing By Default
If you have mailable classes that you want to always be queued, you may implement the ShouldQueue
contract on the class. Now, even if you call the send
method when mailing, the mailable will still be queued since it implements the contract:
1use Illuminate\Contracts\Queue\ShouldQueue;23class OrderShipped extends Mailable implements ShouldQueue4{5 //6}
1use Illuminate\Contracts\Queue\ShouldQueue;23class OrderShipped extends Mailable implements ShouldQueue4{5 //6}
Queued Mailables & Database Transactions
When queued mailables are dispatched within database transactions, they may be processed by the queue before the database transaction has committed. When this happens, any updates you have made to models or database records during the database transaction may not yet be reflected in the database. In addition, any models or database records created within the transaction may not exist in the database. If your mailable depends on these models, unexpected errors can occur when the job that sends the queued mailable is processed.
If your queue connection's after_commit
configuration option is set to false
, you may still indicate that a particular queued mailable should be dispatched after all open database transactions have been committed by calling the afterCommit
method when sending the mail message:
1Mail::to($request->user())->send(2 (new OrderShipped($order))->afterCommit()3);
1Mail::to($request->user())->send(2 (new OrderShipped($order))->afterCommit()3);
Alternatively, you may call the afterCommit
method from your mailable's constructor:
1<?php23namespace App\Mail;45use Illuminate\Bus\Queueable;6use Illuminate\Contracts\Queue\ShouldQueue;7use Illuminate\Mail\Mailable;8use Illuminate\Queue\SerializesModels;910class OrderShipped extends Mailable implements ShouldQueue11{12 use Queueable, SerializesModels;1314 /**15 * Create a new message instance.16 *17 * @return void18 */19 public function __construct()20 {21 $this->afterCommit();22 }23}
1<?php23namespace App\Mail;45use Illuminate\Bus\Queueable;6use Illuminate\Contracts\Queue\ShouldQueue;7use Illuminate\Mail\Mailable;8use Illuminate\Queue\SerializesModels;910class OrderShipped extends Mailable implements ShouldQueue11{12 use Queueable, SerializesModels;1314 /**15 * Create a new message instance.16 *17 * @return void18 */19 public function __construct()20 {21 $this->afterCommit();22 }23}
To learn more about working around these issues, please review the documentation regarding queued jobs and database transactions.
Rendering Mailables
Sometimes you may wish to capture the HTML content of a mailable without sending it. To accomplish this, you may call the render
method of the mailable. This method will return the evaluated HTML content of the mailable as a string:
1use App\Mail\InvoicePaid;2use App\Models\Invoice;34$invoice = Invoice::find(1);56return (new InvoicePaid($invoice))->render();
1use App\Mail\InvoicePaid;2use App\Models\Invoice;34$invoice = Invoice::find(1);56return (new InvoicePaid($invoice))->render();
Previewing Mailables In The Browser
When designing a mailable's template, it is convenient to quickly preview the rendered mailable in your browser like a typical Blade template. For this reason, Laravel allows you to return any mailable directly from a route closure or controller. When a mailable is returned, it will be rendered and displayed in the browser, allowing you to quickly preview its design without needing to send it to an actual email address:
1Route::get('/mailable', function () {2 $invoice = App\Models\Invoice::find(1);34 return new App\Mail\InvoicePaid($invoice);5});
1Route::get('/mailable', function () {2 $invoice = App\Models\Invoice::find(1);34 return new App\Mail\InvoicePaid($invoice);5});
Inline attachments will not be rendered when a mailable is previewed in your browser. To preview these mailables, you should send them to an email testing application such as MailHog or HELO.
Localizing Mailables
Laravel allows you to send mailables in a locale other than the request's current locale, and will even remember this locale if the mail is queued.
To accomplish this, the Mail
facade offers a locale
method to set the desired language. The application will change into this locale when the mailable's template is being evaluated and then revert back to the previous locale when evaluation is complete:
1Mail::to($request->user())->locale('es')->send(2 new OrderShipped($order)3);
1Mail::to($request->user())->locale('es')->send(2 new OrderShipped($order)3);
User Preferred Locales
Sometimes, applications store each user's preferred locale. By implementing the HasLocalePreference
contract on one or more of your models, you may instruct Laravel to use this stored locale when sending mail:
1use Illuminate\Contracts\Translation\HasLocalePreference;23class User extends Model implements HasLocalePreference4{5 /**6 * Get the user's preferred locale.7 *8 * @return string9 */10 public function preferredLocale()11 {12 return $this->locale;13 }14}
1use Illuminate\Contracts\Translation\HasLocalePreference;23class User extends Model implements HasLocalePreference4{5 /**6 * Get the user's preferred locale.7 *8 * @return string9 */10 public function preferredLocale()11 {12 return $this->locale;13 }14}
Once you have implemented the interface, Laravel will automatically use the preferred locale when sending mailables and notifications to the model. Therefore, there is no need to call the locale
method when using this interface:
1Mail::to($request->user())->send(new OrderShipped($order));
1Mail::to($request->user())->send(new OrderShipped($order));
Testing Mailables
Laravel provides several convenient methods for testing that your mailables contain the content that you expect. These methods are: assertSeeInHtml
, assertDontSeeInHtml
, assertSeeInText
, and assertDontSeeInText
.
As you might expect, the "HTML" assertions assert that the HTML version of your mailable contains a given string, while the "text" assertions assert that the plain-text version of your mailable contains a given string:
1use App\Mail\InvoicePaid;2use App\Models\User;34public function test_mailable_content()5{6 $user = User::factory()->create();78 $mailable = new InvoicePaid($user);910 $mailable->assertSeeInHtml($user->email);11 $mailable->assertSeeInHtml('Invoice Paid');1213 $mailable->assertSeeInText($user->email);14 $mailable->assertSeeInText('Invoice Paid');15}
1use App\Mail\InvoicePaid;2use App\Models\User;34public function test_mailable_content()5{6 $user = User::factory()->create();78 $mailable = new InvoicePaid($user);910 $mailable->assertSeeInHtml($user->email);11 $mailable->assertSeeInHtml('Invoice Paid');1213 $mailable->assertSeeInText($user->email);14 $mailable->assertSeeInText('Invoice Paid');15}
Testing Mailable Sending
We suggest testing the content of your mailables separately from your tests that assert that a given mailable was "sent" to a specific user. To learn how to test that mailables were sent, check out our documentation on the Mail fake.
Mail & Local Development
When developing an application that sends email, you probably don't want to actually send emails to live email addresses. Laravel provides several ways to "disable" the actual sending of emails during local development.
Log Driver
Instead of sending your emails, the log
mail driver will write all email messages to your log files for inspection. Typically, this driver would only be used during local development. For more information on configuring your application per environment, check out the configuration documentation.
HELO / Mailtrap / MailHog
Alternatively, you may use a service like HELO or Mailtrap and the smtp
driver to send your email messages to a "dummy" mailbox where you may view them in a true email client. This approach has the benefit of allowing you to actually inspect the final emails in Mailtrap's message viewer.
If you are using Laravel Sail, you may preview your messages using MailHog. When Sail is running, you may access the MailHog interface at: http://localhost:8025
.
Using A Global to
Address
Finally, you may specify a global "to" address by invoking the alwaysTo
method offered by the Mail
facade. Typically, this method should be called from the boot
method of one of your application's service providers:
1use Illuminate\Support\Facades\Mail;23/**4 * Bootstrap any application services.5 *6 * @return void7 */8public function boot()9{10 if ($this->app->environment('local')) {12 }13}
1use Illuminate\Support\Facades\Mail;23/**4 * Bootstrap any application services.5 *6 * @return void7 */8public function boot()9{10 if ($this->app->environment('local')) {12 }13}
Events
Laravel fires two events during the process of sending mail messages. The MessageSending
event is fired prior to a message being sent, while the MessageSent
event is fired after a message has been sent. Remember, these events are fired when the mail is being sent, not when it is queued. You may register event listeners for this event in your App\Providers\EventServiceProvider
service provider:
1/**2 * The event listener mappings for the application.3 *4 * @var array5 */6protected $listen = [7 'Illuminate\Mail\Events\MessageSending' => [8 'App\Listeners\LogSendingMessage',9 ],10 'Illuminate\Mail\Events\MessageSent' => [11 'App\Listeners\LogSentMessage',12 ],13];
1/**2 * The event listener mappings for the application.3 *4 * @var array5 */6protected $listen = [7 'Illuminate\Mail\Events\MessageSending' => [8 'App\Listeners\LogSendingMessage',9 ],10 'Illuminate\Mail\Events\MessageSent' => [11 'App\Listeners\LogSentMessage',12 ],13];