How to Send Emails with Laravel

Dayana Mayfield

Engineering

Close Banner

Free Template & Financial Spreadsheet

Create your SaaS business plan

Sign Up

Editor's note: this is a guest post written by Andriy Zapisotskyi, Growth Manager at Mailtrap.

Laravel is among the most popular PHP frameworks. Developers value it for its simplicity, scalability, speed, and many others. To no surprise, sending emails with the framework is also far from difficult. Let’s see how it’s done.

What’s Laravel mail function about?

Laravel is widely used for building websites, marketplaces, web apps, and even frameworks. It’s excellent if you need to quickly build an MVP. But it’s also a common choice for established businesses that want to take advantage of this constantly growing framework.
The mail function is essential for these tasks - to send transactional emails, newsletters, product updates, and many more.
Just as PHP provides its PHP mail function, Laravel also offers an API for sending emails over the SwiftMailer library. And it’s a lot more reliable. It comes with a number of functionalities:

  • A number of drivers for sending emails through local or cloud-based services. The available API drivers are Mailgun, Postmark, Amazon SES, and sendmail.

  • Ability to send also via SMTP, with Mailtrap being the default SMTP server.

  • Options for queueing emails.

  • Markdown support, which is available only in a few other frameworks. It lets you create beautiful templates and easily include buttons, tables, panels, or even infographics.

  • Regular plain text and HTML messages.

  • Attaching files of different formats and MIME types, as well as raw data, inline attachments, and even embedding raw data into mail templates.

  • Templating system, which lets you use various templates and configure the view.

  • Message previews in-browser.

In addition, there are some noteworthy options:

  • Localization methods, so that you can set the desired language for a specific user.

  • Local development mailing. This is how you can prevent sending test emails to real inboxes. Mailtrap is one of the preferred options.

Building email in Laravel

One more thing that devs appreciate about Laravel is its documentation. It’s clear, straight to the point, and covers everything you need to get started with any of the features. Emails are no exception. For that reason, I’m not going to cover what’s already well covered in Laravel Docs.
Instead, let’s focus on building and sending examples of emails with the framework. And it’s very easy to do.
Here are a couple of basic things to keep in mind:

  • Laravel includes its own command-line interface called Artisan. (Yes, it definitely refers to their slogan “The PHP framework for web artisans”). It provides a bundle of useful commands, for email creation in particular. To get all available commands, type:
    php artisan

    • Each email category can be represented as a “mailable”. It’s a class responsible for building a specific email message using a set of methods. For example:

    php artisan make:mail NewUserNotification

    command generates a class, which you’ll find at ‘app/Mail/NewUserNotification.php. The build() method of this class creates email messages:

    carbon

    This way, we have written a mailable with a build() method. Of course, it’s a minimal example, but you can make the necessary configuration and the next time you need to send it again, you will just type:

    Mail::to($emailAddress)->send(new NewUserNotification);

    Note: Mailables were introduced in Laravel 5.3.

    Sending email in Laravel

    First of all, we need to select the driver. As I mentioned earlier, both API and SMTP drivers are available. For the configuration details, kindly refer to the Driver Prerequisites section.
    In this example, we’ll use the default SMTP option - Mailtrap. Note that since it works as an isolated testing environment, no emails will be sent to actual email addresses. Instead, you’ll be able to view them in your Mailtrap dashboard (you’ll need an account for that).
    Let’s start by defining an SMTP server and setting the mailing configuration. Replace the driver’s configuration in the .env file with your individual Mailtrap credentials, for example:

    2

    You’ll find the credentials for Laravel integration in your Mailtrap dashboard, in the Integrations tab.

    We assume that you have been already using Laravel for building your application. If you were working in one of the previous versions, update your laravel/framework dependency to 7.0.* in your composer.json file, as recommended in the official guide.

    In most cases, the .env file configuration is enough. But alternatively, you can set your config/mail.php file to the following string (also available on the list):

    3

    This way, we have created a Mailable class, with the name MailtrapExample.php. Now we should find it in the Mail directory in app/Mail. We have a template, which contains basic needed functions so that we should just modify it.

    4

    Now it’s time to create the body of our message. For this purpose, we will use a Blade template. We have specified that our mailable is located in the mails.exmpl. Now we need to create a ‘mails’ directory with a blade template file ‘exmpl.blade.php’. inside. Templates represent views in Laravel, so keep the template file in the resources/views/mails directory.

    5

    We’ve added a sender, a subject, a couple of variables and introduced the Markdown support.

    Our simple configuration is done, and we can move forward with sending our message. Specify the route in the routes/web.php:

    6

If you followed all steps, the following email should now hit your Mailtrap inbox:

Verify if the result matches your expectations: if all elements are displayed correctly and links work properly. View the Check HTML and Analysis tabs in Mailtrap to make sure your messages won’t be considered spam and will be rendered correctly in most email clients.

Once you are satisfied with the results of tests, replace SMTP configurations with your production server or configure any other option to send emails to real inboxes. In general, API drivers are recommended. They’re faster than SMTP and usually enjoy much better deliverability. 

But if you opt for SMTP, you can also configure a number of tools to send emails on your behalf. If you’re aiming for a budget option, you can, for example, utilize Gmail’s SMTP server. Whichever way you go, you shouldn’t have much trouble setting things up in Laravel whether you're building an MVP, marketplaces, web apps, and even frameworks.

Authors-

Editor's note: this is a guest post written by Andriy Zapisotskyi, Growth Manager at Mailtrap.

Close Banner

Building a product?

Discover the DevSquad Difference

Learn More