Laravel Mailable: The new and improved way to send email in Laravel

Tutorials

August 10th, 2016

laravel-mailables.jpg

A new feature in Laravel 5.3 is a way to simplify sending email by creating “mailable” classes that handle setting up your emails.

The best way to explain this feature is with an example. In Laravel 5.2 you would typically send an email like the following that is outlined in the documentation:

1Mail::send('emails.reminder', ['user' => $user], function ($m) use ($user) {
2 $m->from('hello@app.com', 'Your Application');
3 $m->to($user->email, $user->name)->subject('Your Reminder!');
4});

A lot is going on in those four lines of code. You pass a view, data to assign to the view, use the “user” in the closure, and finally setup your message.

Now in Laravel 5.3 you can simplify this by utilizing a “mailable” class.

1php artisan make:mail YourReminder

Next, open the new class that is created and all of a mailable configuration is done in the build method. Within this, you may call various methods such as from, subject, view, and attach to configure the email’s presentation and delivery. Here is a minimal example:

1public function build()
2{
3 return $this->from('example@example.com')
4 ->view('emails.reminder');
5}

Now, anytime you want to send this email you can call it like this:

1Mail::to($email)->send(new YourReminder);

All of the existing mail features still work. You can queue, add cc, bcc, attach files and more.

If you’d like to learn more about Laravel Mailable here are a few resources to help you on your journey:

Filed in:

Eric L. Barnes

Eric is the creator of Laravel News and has been covering Laravel since 2012.