Sending emails in Laravel. A step-by-step tutorial

Subscribe to our monthly newsletter to get the latest news and handpicked content delivered to your inbox.

BACK

October 31st, 2022, posted in Guest Posts
by Yurii Shumak

Setting up email sending in Laravel while creating a web application is usually an essential part − you would want to register new users or notify old ones of any changes or promotions. Thus, you need to take care of authentication tokens, expiration dates, authentication processes, etc. Here, we will discuss how you can send emails from Laravel application and integrate third-party services to manage subscribers and send emails on time.

 

Working with Laravel Mail

Creating the Mailable Class

Instead of using the Mail facade in Laravel to send emails, you may use Laravel Mailables, which are dedicated classes for composing and sending emails in a cleaner and more abstract way.

Initially, you can create mailable classes using the artisan command:

php artisan make:mail ProductApproved

 

ProductApproved.php will be nested inside app/Mail/ inside the app/directory. You may see this structure when opening the class:

 

<?php

namespace App\\Mail;

use Illuminate\\Bus\\Queueable;

use Illuminate\\Mail\\Mailable;

use Illuminate\\Queue\\SerializesModels;

use Illuminate\\Contracts\\Queue\\ShouldQueue;

class ProductApproved extends Mailable

{

    use Queueable, SerializesModels;

    /**

     * Create a new message instance.

     *

     * @return void

     */

    public function __construct()

    {

        //

    }

 

    /**

     * Build the message.

     *

     * @return $this

     */

    public function build()

    {

        return $this->view('view.name');

    }

}

 

The build() method is the most crucial one described here, as it composes and configures the mail message by rendering the email template. As shown below, it just returns the mail template view, but you may also utilize other methods like setting the from using the from() method, setting the subject using the subject() method, and attaching files using the attach() method.

 

public function build()

{

    return $this->from('[email protected]')

                ->view('view.name')

                ->text('view.name_text');

}

 

You would define the Welcome email address using the Form Method.

You would define the email subject using the Subject Method.

You can also use Attach to define attachments – for example, if you send emails with attachments, etc.

You can use the view method to specify the template that should be used to present the content of the email if you want to send an email.

Instead of creating a new mailable class for each email, you can just type:

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

 

Creating the Laravel Email Template

<div>

   Name: {{ $name }}

</div>

 

Sending an email in Laravel

Laravel's developers suggest using one of the API-based drivers. It can be Mailgun, Postmark,  Amazon SES or Mailtrap email API. You can send emails in a variety of ways.

In the mail configuration file (for example, Mailgun), you may set one of the multiple drivers introduced in Laravel 9.0 as the default one.

Furthermore, you may use any SMTP server you want, such as Gmail. The configurations are made in the config/mail.php file in the default Laravel setup. To edit the email configuration in Laravel, you should save your changes to the .env file (which you can find in the root directory). To do this, you must edit the email configuration in the .env file (which you can find in the root directory).

Using Mailtrap's SMTP server is one of Laravel's suggested methods for sending emails. It prevents accidental delivery of test emails to real inboxes by trapping these messages for debugging.

To ensure that your message is delivered to your own or your customer's inbox, remember to modify the configuration to match the real server.

MAIL_MAILER=smtp

MAIL_HOST=smtp.googlemail.com

MAIL_PORT=465

[email protected]

MAIL_PASSWORD=your password

MAIL_ENCRYPTION=ssl

 

Sending emails with Laravel using SMTP

An SMTP server is cost-efficient and optimized for fast and efficient email delivery. It also reduces the likelihood that mass emails you send will be incorrectly labelled as spam.

In this example, we’ll use Mailtrap as an SMTP server and set up a mailing configuration.

All you have to do is enter your credentials. You can find them in the SMTP Settings tab of your Inbox or use Integrations data from the same tab. Select Laravel from the list, copy the following information, and paste it into your .env file.

MAIL_MAILER=smtp

MAIL_HOST=smtp.mailtrap.io

MAIL_PORT=2525

MAIL_USERNAME=1a2b3c4d5e6f7g //your username

MAIL_PASSWORD=1a2b3c4d5e6f7g // your password

[email protected]

MAIL_FROM_NAME=Example

 

Look for the mailables we created earlier:

php artisan make:mail NewUserNotification

A route should be specified in routes/web.php to add a sender, a subject, and a body massage, as well as Markdown support:

<?php

use App\\Mail\\MailtrapExample;

use Illuminate\\Support\\Facades\\Mail;

Route::get('/send-mail', function () {

Mail::to('[email protected]')->send(new MailtrapExample());

return 'A message has been sent to Mailtrap!';

});

 

Integrate Mailtrap with Laravel

You just have to type in your credentials in the default server in Mailtrap. Install Laravel using Cloudways Managed Hosting Platform and enter the following configurations in the .env file.

MAIL_DRIVER=smtp

MAIL_HOST=smtp.mailtrap.io

MAIL_PORT=2525

MAIL_USERNAME= //your username generated by Mailtrap

MAIL_PASSWORD= // your password generated by Mailtrap

[email protected]

MAIL_FROM_NAME=Example

 

The .env file configuration is usually sufficient. Alternatively, you can set your config/mail.php file to the following content (it is also available in the list of integrations in Mailtrap):

<?php

return [

 "driver" => "smtp",

 "host" => "smtp.mailtrap.io",

 "port" => 2525,

 "from" => array(

     "address" => "[email protected]",

     "name" => "Example"

 ),

 "username" => "1a2b3c4d5e6f7g" // your username,

 "password" => "1a2b3c4d5e6f7g" // your password,

 "sendmail" => "/usr/sbin/sendmail -bs"

];

 

Create Mailable Class For Mailtrap

Here is the command to create a Mailable class on SSH Terminal.

php artisan make:mail MailtrapExample

Moreover, you must look for the Mail directory in the app/Mail to find the template. You can alter that template using the following code with basic functions:

<?php

namespace App\\Mail;

use Illuminate\\Bus\\Queueable;

use Illuminate\\Mail\\Mailable;

use Illuminate\\Queue\\SerializesModels;

use Illuminate\\Contracts\\Queue\\ShouldQueue;

class MailtrapExample extends Mailable

{

   use Queueable, SerializesModels;

   /**

    * Create a new message instance.

    *

    * @return void

    */

   public function __construct()

   {

      //

   }

   /**

    * Build the message.

    *

    * @return $this

    */

public function build()

   {

       return $this->from('[email protected]', 'Mailtrap')

           ->subject('Mailtrap Confirmation')

           ->markdown('mails.exmpl')

           ->with([

               'name' => 'New Mailtrap User',

               'link' => '<https://mailtrap.io/inboxes>'

           ]);

   }


Next, you must create a message for this in the blade.php file. For this example, I've specified the mailable class in the mails.exmpl. To finish, you must create a 'mails' directory with a blade template file 'emailexample.blade.php'.

 

To Sum Up

Production-ready applications rely on sending emails, and this article explains how to set up a Simple Mail Implementation in Laravel and configure Gmail's SMTP server. Through transactional emails, you can automate some of the necessary features for an effective application.

 


About the author

Yurii Shumak

I'm a technical content writer and Mailtrap contributor passionate about helping companies and products bridge the gap between people, processes, and technology. In other words: the trenches are where I spend most of my time.

See more articles by Yurii Shumak