Mail

Introduction

Laravel provides a clean, simple API over the popular SwiftMailer library with drivers for SMTP, Mailgun, SparkPost, Amazon SES, PHP's mail function, and sendmail, allowing you to quickly get started sending mail through a local or cloud based service of your choice.

Driver Prerequisites

The API based drivers such as Mailgun and SparkPost are often simpler and faster than SMTP servers. If possible, you should use one of these drivers. All of the API drivers require the Guzzle HTTP library, which may be installed via the Composer package manager:

  1. composer require guzzlehttp/guzzle

Mailgun Driver

To use the Mailgun driver, first install Guzzle, then set the driver 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' => 'your-mailgun-domain',
  3. 'secret' => 'your-mailgun-key',
  4. ],

SparkPost Driver

To use the SparkPost driver, first install Guzzle, then set the driver option in your config/mail.php configuration file to sparkpost. Next, verify that your config/services.php configuration file contains the following options:

  1. 'sparkpost' => [
  2. 'secret' => 'your-sparkpost-key',
  3. ],

SES Driver

To use the Amazon SES driver you must first install the Amazon AWS SDK for PHP. You may install this library by adding the following line to your composer.json file's require section and running the composer update command:

  1. "aws/aws-sdk-php": "~3.0"

Next, set the driver 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' => 'your-ses-key',
  3. 'secret' => 'your-ses-secret',
  4. 'region' => 'ses-region', // e.g. us-east-1
  5. ],

Generating Mailables

In Laravel, 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 command:

  1. php artisan make:mail OrderShipped

Writing Mailables

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.

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 $this
  5. */
  6. public function build()
  7. {
  8. return $this->from('[email protected]')
  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:

  1. 'from' => ['address' => '[email protected]', 'name' => 'App Name'],

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 $this
  5. */
  6. public function build()
  7. {
  8. return $this->view('emails.orders.shipped');
  9. }

{tip} 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 a HTML and plain-text version of your message:

  1. /**
  2. * Build the message.
  3. *
  4. * @return $this
  5. */
  6. public 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. <?php
  2. namespace App\Mail;
  3. use App\Order;
  4. use Illuminate\Bus\Queueable;
  5. use Illuminate\Mail\Mailable;
  6. use Illuminate\Queue\SerializesModels;
  7. class OrderShipped extends Mailable
  8. {
  9. use Queueable, SerializesModels;
  10. /**
  11. * The order instance.
  12. *
  13. * @var Order
  14. */
  15. public $order;
  16. /**
  17. * Create a new message instance.
  18. *
  19. * @return void
  20. */
  21. public function __construct(Order $order)
  22. {
  23. $this->order = $order;
  24. }
  25. /**
  26. * Build the message.
  27. *
  28. * @return $this
  29. */
  30. public function build()
  31. {
  32. return $this->view('emails.orders.shipped');
  33. }
  34. }

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>

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. <?php
  2. namespace App\Mail;
  3. use App\Order;
  4. use Illuminate\Bus\Queueable;
  5. use Illuminate\Mail\Mailable;
  6. use Illuminate\Queue\SerializesModels;
  7. class OrderShipped extends Mailable
  8. {
  9. use Queueable, SerializesModels;
  10. /**
  11. * The order instance.
  12. *
  13. * @var Order
  14. */
  15. protected $order;
  16. /**
  17. * Create a new message instance.
  18. *
  19. * @return void
  20. */
  21. public function __construct(Order $order)
  22. {
  23. $this->order = $order;
  24. }
  25. /**
  26. * Build the message.
  27. *
  28. * @return $this
  29. */
  30. public function build()
  31. {
  32. return $this->view('emails.orders.shipped')
  33. ->with([
  34. 'orderName' => $this->order->name,
  35. 'orderPrice' => $this->order->price,
  36. ]);
  37. }
  38. }

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>

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 $this
  5. */
  6. public 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 $this
  5. */
  6. public 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. }

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 $this
  5. */
  6. public 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 and retrieving the appropriate CID. 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:
  3. <img src="{{ $message->embed($pathToFile) }}">
  4. </body>

Embedding Raw Data Attachments

If you already have a raw data string you wish to embed into an email template, you may use the embedData method on the $message variable:

  1. <body>
  2. Here is an image from raw data:
  3. <img src="{{ $message->embedData($data, $name) }}">
  4. </body>

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 setting the email 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. <?php
  2. namespace App\Http\Controllers;
  3. use App\Order;
  4. use App\Mail\OrderShipped;
  5. use Illuminate\Http\Request;
  6. use Illuminate\Support\Facades\Mail;
  7. use App\Http\Controllers\Controller;
  8. class OrderController extends Controller
  9. {
  10. /**
  11. * Ship the given order.
  12. *
  13. * @param Request $request
  14. * @param int $orderId
  15. * @return Response
  16. */
  17. public function ship(Request $request, $orderId)
  18. {
  19. $order = Order::findOrFail($orderId);
  20. // Ship order...
  21. Mail::to($request->user())->send(new OrderShipped($order));
  22. }
  23. }

Of course, you are not limited to just specifying the "to" recipients when sending a message. You are free to set "to", "cc", and "bcc" recipients all within a single, chained method call:

  1. Mail::to($request->user())
  2. ->cc($moreUsers)
  3. ->bcc($evenMoreUsers)
  4. ->send(new OrderShipped($order));

Queueing Mail

Queueing A Mail Message

Since sending email messages can drastically lengthen 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:

  1. Mail::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. Of course, 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:

  1. $when = Carbon\Carbon::now()->addMinutes(10);
  2. Mail::to($request->user())
  3. ->cc($moreUsers)
  4. ->bcc($evenMoreUsers)
  5. ->later($when, 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');
  4. Mail::to($request->user())
  5. ->cc($moreUsers)
  6. ->bcc($evenMoreUsers)
  7. ->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:

  1. use Illuminate\Contracts\Queue\ShouldQueue;
  2. class OrderShipped extends Mailable implements ShouldQueue
  3. {
  4. //
  5. }

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. For more information on configuring your application per environment, check out the configuration documentation.

Universal To

Another solution provided by Laravel is to set a universal recipient of all emails sent by the framework. This way, all the emails generated by your application will be sent to a specific address, instead of the address actually specified when sending the message. This can be done via the to option in your config/mail.php configuration file:

  1. 'to' => [
  2. 'address' => '[email protected]',
  3. 'name' => 'Example'
  4. ],

Mailtrap

Finally, you may use a service like 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.

Events

Laravel fires an event just before sending mail messages. Remember, this event is fired when the mail is sent, not when it is queued. You may register an event listener for this event in your EventServiceProvider:

  1. /**
  2. * The event listener mappings for the application.
  3. *
  4. * @var array
  5. */
  6. protected $listen = [
  7. 'Illuminate\Mail\Events\MessageSending' => [
  8. 'App\Listeners\LogSentMessage',
  9. ],
  10. ];