sending emails with laravel

Email sending is an essential feature for any web application to keep connected with the users and run your marketing. Of course, there are different ways to send emails with PHP, but the Laravel framework is one of the best options out there. So why choose Laravel and how to send emails with Laravel? Read next.

Why you should choose Laravel for sending emails

Laravel is a PHP framework that is used to build web apps and websites. Because of its connectivity and modernity, sending emails using Laravel is easy — you get the following capabilities:

  • integrations for email sending through both local and cloud services
  • email queuing
  • support of Markdown
  • HTML emails
  • attachments and embedding of different media types
  • email templates
  • in-browser previews
  • localization

As you can see, the framework provides everything you need for your email sending.

Installation of Laravel

The steps you have to take to install Laravel on your machine will depend on the operating system you’re using. But alternatively, you can also install Laravel via installing Sail, a built-in solution for Laravel, to Docker. This is an easy way of completing your Laravel installation recommended in the official documentation.

The framework also offers the Mail API, which provides a vast range of email drivers through the Symfony Mailer component. Let’s discuss how we can set it up.

Initial Setup Requirements

To set up the component’s initial configurations, access config/mail.php to see the default settings for email sending:

 

<?php

 

return [

 

    ‘default’ => env(‘MAIL_MAILER’, ‘smtp’),

 

    ‘mailers’ => [

        ‘smtp’ => [

            ‘transport’ => ‘smtp’,

            ‘host’ => env(‘MAIL_HOST’, ‘smtp.mailgun.org’),

            ‘port’ => env(‘MAIL_PORT’, 587),

            ‘encryption’ => env(‘MAIL_ENCRYPTION’, ‘tls’),

            ‘username’ => env(‘MAIL_USERNAME’),

            ‘password’ => env(‘MAIL_PASSWORD’),

            ‘timeout’ => null,

            ‘auth_mode’ => null,

        ],

As you can see, the mail driver is set to SMTP. To set the values for your server or change the driver to something else, apply changes in the .env file.

You can also use other drivers like mailgun, sendmail, ses, etc. — these are all supported as well:

 

        ‘ses’ => [

            ‘transport’ => ‘ses’,

        ],

 

        ‘mailgun’ => [

            ‘transport’ => ‘mailgun’,

        ],

 

        ‘postmark’ => [

            ‘transport’ => ‘postmark’,

        ],

 

        ‘sendmail’ => [

            ‘transport’ => ‘sendmail’,

            ‘path’ => ‘/usr/sbin/sendmail -bs’,

        ],

 

        ‘log’ => [

            ‘transport’ => ‘log’,

            ‘channel’ => env(‘MAIL_LOG_CHANNEL’),

        ],

 

        ‘array’ => [

            ‘transport’ => ‘array’,

        ],

    ],

Besides, you can use the following in case if all your emails are sent from the same address:

 

    ‘from’ => [

        ‘address’ => env(‘MAIL_FROM_ADDRESS’, ‘hello@example.com’),

        ‘name’ => env(‘MAIL_FROM_NAME’, ‘Example’),

    ],

And of course, you can customize your emails, or stick to Laravel’s default configurations:

 

    ‘markdown’ => [

        ‘theme’ => ‘default’,

 

        ‘paths’ => [

            resource_path(‘views/vendor/mail’),

        ],

    ],

 

];

There you go — now you have the setup for the mail API configurations.

Create the Mailable Class

Next, you have to create the Mailable class to send emails, which you can do through an artisan command:

php artisan make:mail DemoEmail

Now you have a blank template at app/Mail/DemoEmail.php, which we will further fill in to get a ready-to-use one. 

Core points of working with Laravel Mail

To learn how to send emails using Laravel, you need to know how to build an email, create a template and actually send the message with the framework. Here are the guidelines on how to do each of these. 

sending emails with laravel
Source: Freepik

 

How to build an email in Laravel

After you create the Mailable class, you can now get to building an email message. To do that, refer to the following:  

<?php

 

namespace App\Mail;

 

use Illuminate\Bus\Queueable;

use Illuminate\Contracts\Queue\ShouldQueue;

use Illuminate\Mail\Mailable;

use Illuminate\Queue\SerializesModels;

 

class DemoEmail extends Mailable

{

    use Queueable, SerializesModels;

      

    public $demo

    public function __construct($demo)

    {

        $this->demo = $demo;

    }

      public function build()

    {

        return $this->from(‘sender@example.com’)

                    ->view(‘mails.demo’)

                    ->text(‘mails.demo_plain’)

                    ->with(

                      [

                            ‘testVarOne’ => ‘1’,

                            ‘testVarTwo’ => ‘2’,

                      ])

                      ->attach(public_path(‘/images’).’/demo.jpg’, [

                              ‘as’ => ‘demo.jpg’,

                              ‘mime’ => ‘image/jpeg’,

                      ]);

    }

}

 As you can see, there are several methods used:

  • __consruct initializes objects used in the template
  • build is used to initialize other values like attachment and view
  • mails.demo sets the view of the email according to the email template from resources/views/mails/demo.blade.php
  • text sets the simple text version of the email
  • attach attaches an image to the email from public/images/demo.jpg

Let’s see how we can use the file we’ve just created to build an actual email message with a template.

Creating the Laravel Email Template

Let’s create a template for the email in the resources/views/mails/demo.blade.php file:

Hello <i>{{ $demo->receiver }}</i>,

<p>This is a demo email for testing purposes! Also, it’s the HTML version.</p>

  

<p><u>Demo object values:</u></p>

  

<div>

<p><b>Demo One:</b>&nbsp;{{ $demo->demo_one }}</p>

<p><b>Demo Two:</b>&nbsp;{{ $demo->demo_two }}</p>

</div>

  

<p><u>Values passed by With method:</u></p>

  

<div>

<p><b>testVarOne:</b>&nbsp;{{ $testVarOne }}</p>

<p><b>testVarTwo:</b>&nbsp;{{ $testVarTwo }}</p>

</div>

  

Thank You,

<br/>

<i>{{ $demo->sender }}</i>

Then, let’s create the plain text version:

Hello {{ $demo->receiver }},

This is a demo email for testing purposes! Also, it’s the HTML version.

  

Demo object values:

  

Demo One: {{ $demo->demo_one }}

Demo Two: {{ $demo->demo_two }}

  

Values passed by With method:

  

testVarOne: {{ $testVarOne }}

testVarOne: {{ $testVarOne }}

  

Thank You,

{{ $demo->sender }}

Now you have an email template created via the Mailable class that is ready to be used.

Sending an email with Laravel

To send an email using Laravel and the Mailable class you’ve just created, start with creating a blank controller file at app/Http/Controllers/MailController.php:

php artisan make:controller MailController

Replace the contents of the file with the following:

<?php

namespace App\Http\Controllers;

  

use App\Http\Controllers\Controller;

use App\Mail\DemoEmail;

use Illuminate\Support\Facades\Mail;

  

class MailController extends Controller

{

    public function send()

    {

        $objDemo = new \stdClass();

        $objDemo->demo_one = ‘Demo One Value’;

        $objDemo->demo_two = ‘Demo Two Value’;

        $objDemo->sender = ‘SenderUserName’;

        $objDemo->receiver = ‘ReceiverUserName’;

  

        Mail::to(“receiver@example.com”)->send(new DemoEmail($objDemo));

    }

}

As you can see, we’re using the Illuminate\Support\Facades\Mail Facade to send the email, while the send method initializes Mailable.

Now, you can test whether your email sending works. You can go two ways for this:

  • add the needed route to the routes/web.php file:

Route::get(‘mail/send’, ‘MailController@send’);

  • go to the config/mail.php file and set the value of MAIL_DRIVER to log, run the link mentioned above and check whether your template was logged to storage/logs/laravel.log — if yes, then email sending works fine.

Note that option b) doesn’t involve sending any actual emails being sent; it just adds logs to the file instead. 

Laravel versions

Laravel used to release a new version to fix bugs every half a year and to fix security issues annually. Now, the releases of new versions for all fixes will be annual to sync them with the releases of the Symphony framework.

The latest version of Laravel available in October 2022 is version 9 (LTS), which is suitable for PHP versions 8 or newer. As for what’s new in Laravel 9 (LTS), this update:

  • requires PHP 8
  • features Symfony Mailer instead of Swift Mailer and a new Laravel Scout database engine
  • enables the use of controller route groups, fulltext indexes and where clauses
  • offers improved accessors and mutators in Eloquent
  • provides other capabilities earlier unavailable

Interestingly, Laravel provides long-term support (LTS), 2 years for bug fixes and 3 years for security fixes. So the current version 9 released on February 8th, 2022 provides support for bug fixes until February 8th, 2024, and security fixes until February 8th, 2025.

It’s important to note that version 9 of Laravel replaces version 6, the long-term support of which expired in September of 2022. At the same time, versions 7 and 8 are no longer supported, so users have to upgrade from these versions to Laravel 9 (LTS).

Sending an email in Laravel using SMTP

Now that we’ve discussed how to send emails with Laravel, let’s see how we can set up email sending using SMTP in the framework.

Configurations for Laravel Gmail SMTP

To set up Gmail SMTP in Laravel, we need to start with the configuration of the basic settings. Use the following to update the .env file:

MAIL_DRIVER=smtp

MAIL_HOST=smtp.googlemail.com

MAIL_PORT=465

MAIL_USERNAME=ENTER_YOUR_EMAIL_ADDRESS(GMAIL)

MAIL_PASSWORD=ENTER_YOUR_GMAIL_PASSWORD

MAIL_ENCRYPTION=ssl

Next, there are some security settings in the Gmail account that need to be changed. So go to your Google account settings, then Security, and check the security setting. That’s it on Gmail account settings.

The next step is sending an email with Laravel through Gmail SMTP. Create a controller and insert the following:

public function mail()

{

$to_name = ‘RECEIVER_NAME’;

$to_email = ‘RECEIVER_EMAIL_ADDRESS’;

$data = array(‘name’=>”Cloudways (sender_name)”, “body” => “A test mail”);

  

Mail::send(‘mail’, $data, function($message) use ($to_name, $to_email) {

$message->to($to_email, $to_name)

->subject(Laravel Test Mail’);

$message->from(‘SENDER_EMAIL_ADDRESS’,’Test Mail’);

});

   

   return ‘Email sent Successfully’;

}

Now, create a Blade file and name it mail.blade.php, then insert the following code:

Hello <b>{{ $name }}</b>,

<p>{{body}}</p>

There it is — you have Gmail SMTP all set to send your emails.

Integrate Mailtrap with Laravel

Another way of using SMTP in Laravel is by integrating the Mailtrap email delivery platform into it. This way you will be able to test bulk email campaigns, add email verification in Laravel and get other capabilities for your email sending. Let’s see how to set up the integration using Laravel 7.

To define the SMTP server for your mailing, insert the following to your .env file:

MAIL_MAILER=smtp

MAIL_HOST=smtp.mailtrap.io

MAIL_PORT=2525

MAIL_USERNAME=1a2b3c4d5e6f7g

MAIL_PASSWORD=1a2b3c4d5e6f7g

MAIL_FROM_ADDRESS=from@example.com

MAIL_FROM_NAME=Example

As you can see, the host is already set to Mailtrap’s fake SMTP server. Now, you have to update the rest of the values, like username, password, address and name, with your credentials and accurate information. 

Next, we have to create a Mailable class named MailtrapExample.php, which will be located in app/Mail. To do this, run the following:

php artisan make:mail MailtrapExample

Next, we can modify the template to set the email configurations ready, like adding a sender, a subject of the email and introducing the support of Markdown:

<?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(‘mail@example.com’, ‘Mailtrap’)

            ->subject(‘Mailtrap Confirmation’)

            ->markdown(‘mails.exmpl’)

            ->with([

                ‘name’ => ‘New Mailtrap User’,

                ‘link’ => ‘/inboxes/’

            ]);

    }

It’s time to work on the body of the email message using a Blade template — create a directory with the template file in mails.exmpl and run the following:

@component(‘mail::message’)

Hello **{{$name}}**,  {{– use double space for line break –}}

Thank you for choosing Mailtrap!

Click below to start working right now

@component(‘mail::button’, [‘url’ => $link])

Go to your inbox

@endcomponent

Sincerely,

Mailtrap team.

@endcomponent

Next, we can edit the routes/web.php to specify the route for email sending:

<?php

use App\Mail\MailtrapExample;

use Illuminate\Support\Facades\Mail;

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

    Mail::to(‘newuser@example.com’)->send(new MailtrapExample());

    return ‘A message has been sent to Mailtrap!’;

});

Now you can run your application — run php artisan serve and go to /send-mail in the browser. That’s it, you can see the email message in your Mailtrap inbox!

To Wrap Up

Using PHP Laravel is simple and versatile for sending bulk emails, HTML emails and emails with attachments. Depending on the needs of your campaign, you can choose the most appropriate guidelines described to set up email sending for your web app. 

Sofiia Kasianenko

Software Engineer and Mailtrap Contributor. Sofiia is interested in information technologies across all industries, from marketing to healthcare. Besides writing, she is passionate about creativity, professional growth, fitness, and well-being.