Step-by-Step Guide to Send Emails in Laravel

Today’s businesses need to be as responsive as possible. That’s why more and more companies are turning to SaaS solutions, which allow them to access their data from anywhere.

What’s even better is that almost every software has a modern API that makes integrating it into your app much more effortless.

This blog post will look at best practices for sending emails using Laravel and how to do it correctly and efficiently.

Why you should choose Laravel for sending emails

Laravel provides support for email attachments, formatting, and localization. You can use these features to send coupons, HTML emails, newsletters, and custom messages.

With PHP, software engineers may use Laravel, a PHP framework that optimizes emailing processes, to create apps. Laravel allows you to manage email previews, has various options for localization, and ensures that real users never see test emails in their inboxes.

The majority of queries relating to managing emails in Laravel are addressed by the available documentation and tutorials.

Instead of using PHP’s built-in mail() function to send emails, you may want to use Laravel. Let’s look at each one.

  • Using Laravel’s mail-sending options is more secure because PHP’s function can leave websites open to various attacks, potentially allowing malicious actors to execute arbitrary PHP code on the server.
  • Using Laravel, you can send emails in a controlled and reliable manner, improving your email deliverability. Queuing emails can help reduce the risk of your mail server being listed on anti-spam lists if you’re sending to a large list, especially if you’re sending to a high-volume list.
  • In addition, it supports email attachments, formatting, and localization, and Laravel provides these features. You can use them to send coupons, HTML emails, newsletters, and custom messages.

Creating the Mailable Class

We will create the mailable class in this section, which will be used to send emails. The mailable class is responsible for sending emails using a mailer that is configured in the config/mail.php file. Laravel already provides us with an artisan command to generate a base template.

php artisan make:mail DemoEmail

app/Mail/DemoEmail.php should be created as a blank email template, as shown in the following snippet.

<?php<font></font>
<font></font>
namespace App\\Mail;<font></font>
<font></font>
use Illuminate\\Bus\\Queueable;<font></font>
use Illuminate\\Contracts\\Queue\\ShouldQueue;<font></font>
use Illuminate\\Mail\\Mailable;<font></font>
use Illuminate\\Queue\\SerializesModels;<font></font>
<font></font>
class DemoEmail extends Mailable<font></font>
{<font></font>
    use Queueable, SerializesModels;<font></font>
<font></font>
    /**<font></font>
     * Create a new message instance.<font></font>
     *<font></font>
     * @return void<font></font>
     */<font></font>
    public function __construct()<font></font>
    {<font></font>
        //<font></font>
    }<font></font>
<font></font>
    /**<font></font>
     * Build the message.<font></font>
     *<font></font>
     * @return $this<font></font>
     */<font></font>
    public function build()<font></font>
    {<font></font>
        return $this->view('view.name');<font></font>
    }<font></font>
}

An email template uses two core methods: __construct and build. The __construct method initializes objects that are used in the message. On the other hand, the build method initializes more email-specific values like from, view templates, and attachments.

We’ve used the $demo object as a constructor argument, and we assigned it to the demo public property.

An email-specific configuration has been initialized in the build method.

  • An email address can be set using from.
  • You can set the email template that is used when sending an email using this mailable. In our scenario, we’ve set it to mails.demo, and consequently, you must create a view template file at resources/views/mails/demo.blade.php.
  • An email template can be set up using the text method.
  • The __construct method, as we just discussed, is used to create email templates. You may also use with the method, which lets you specify the view data of a message.
  • We then attached an image to a message using the attach method. Please ensure that the image is available at public/images/demo.jpg.

That was the mailable class you had to take.

Core points of working with Laravel Mail

It is not recommended to use the Artisan server for production purposes, but it is useful for testing and troubleshooting.

Installing Laravel is simple. All you have to do is install Composer, then use it to install Laravel by running:

composer global require laravel/installer

You can create a new instance of your Laravel project once the Laravel installer is installed on your server by entering:

laravel new webapp

It is important to rename webapp to a meaningful name for your venture!

With the above command, a folder called ‘webapp’ (or your project name) will be created that includes everything needed for Laravel, as well as a .htaccess file. You can then point Apache to that folder using the standard Apache configuration file.

You can use the PHP Artisan server to verify that your new, minimalist app runs correctly by running:

php artisan serve

It is not advisable to use the Artisan server for production environments, but it is useful for testing and troubleshooting.

How to build an email in Laravel

In the app/Mail/DemoEmail.php file, we will create a Mail class named php artisan make:mail DemoEmailafter we finish creating it.

You can use the form method to define the email address you want to use.

*/
public function build()
{
   return $this->from('[email protected]')
               ->view('emails.Demo.Email);
}

You can set up mail settings in the mail configuration file in Laravel if your mail is the same across all of our web applications.

First, you must configure the same email address across the whole application in the config/mail.php file. Just copy and paste the following code.

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

You may use the view method to specify which template should be used for mailing when rendering the email’s contents within a mailable class.

public function build()
{
   return $this->view('emails.Demo.Email);
}

Do you want to make data available to the view function when rendering the email’s HTML? There are two ways to pass data to your view.

Any public properties defined in your mailable class are automatically available to view. For example, you may pass data into the constructor of your mailable class and set the public properties to values:

<?php
 
namespace App\\Mail;
 
use Illuminate\\Bus\\Queueable;
use Illuminate\\Mail\\Mailable;
use Illuminate\\Queue\\SerializesModels;
use Illuminate\\Contracts\\Queue\\ShouldQueue;
 
class SendMailable extends Mailable
{
   use Queueable, SerializesModels;
   public $name;
 
 
   public function __construct($name)
   {
       $this->name = $name;
   }
   public function build()
   {
       return $this->view('emails.name');
   }
}

Once the data has been set to public property, it will automatically be available in your view.

Creating the Laravel Email Template

Laravel provides a wide variety of markdown features, including templates for buttons, tables, and panels. The template is a Blade file that can be customized in any way.

The .blade.php extension is used for template files, which are located in the resources/views directory.

The view helper can be used to retrieve Blade views from routes or controllers.

Displaying data can be achieved using the route:

Route::get('/', function () {
    return view('welcome', \\\\\\['name' => 'Yurii']);
});

Displaying the contents of the name variable:

Hello, {{ $name }}.

The AppServiceProvider boot method provides the Blade::withoutDoubleEncoding method to disable double encoding:

<?php
namespace App\\\\\\\\Providers;
use Illuminate\\\\\\\\Support\\\\\\\\Facades\\\\\\\\Blade;
use Illuminate\\\\\\\\Support\\\\\\\\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
    /\\\\\\\\\\*\\\\\\\\\\*
     \\\\\\\\\\* Bootstrap any application services.
     \\\\\\\\\\*
     \\\\\\\\\\* @return void
     \\\\\\\\\\*/
    public function boot()
    {
        Blade::withoutDoubleEncoding();
    }
}

Sending an email with Laravel

In addition to the API-based drivers Mailgun, SparkPost, Amazon SES, and Mailtrap, you may set a default driver in the Laravel email configuration file to send emails. You may also manage specific types of messages:

Mail::mailer('mailtrap')

\\->to($emailAddress())
\\->send(new NewUserNotification));

Sending an email in Laravel using SMTP

To set up a fresh Laravel 9 Framework, I will run the following command in the command prompt or terminal.
composer create-project –prefer-dist laravel/laravel sendEmail

You may use Laravel 9’s email-sending features in your existing Laravel application, even if installing Laravel is not required here.

Run the below command to go to your application directory.

cd sendEmail

After Laravel is installed, configure SMTP and set up all the credentials required for Laravel to send emails.

Configurations for Laravel Gmail SMTP

Make the following modifications to your .env file for Gmail SMTP configuration.

MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
[email protected]
MAIL_PASSWORD=your_password
MAIL_ENCRYPTION=tls
[email protected]
MAIL_FROM_NAME="${APP_NAME}"

To send emails through Gmail, you must enable Less secure app access from your Gmail account settings.

Let’s build a Mail class named SendMail to send our test message. This will refer to the test message view.

Create a Mail class using the given command.

php artisan make:mail SendMail

Update the SendMail.php file on the app/Mail folder to match the code below.

<?php

namespace App\\Mail;

use Illuminate\\Bus\\Queueable;
use Illuminate\\Contracts\\Queue\\ShouldQueue;
use Illuminate\\Mail\\Mailable;
use Illuminate\\Queue\\SerializesModels;

class SendMail extends Mailable
{
    use Queueable, SerializesModels;

    public $testMailData;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($testMailData)
    {
        $this->testMailData = $testMailData;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->subject('Email From AllPHPTricks.com')
                    ->view('emails.testMail');
    }
}

Create an EmailController with an index() method that emails your desired address.

Run the following command to create a mail controller.

php artisan make:controller EmailController

See the app/Http/Controllers/EmailController.php code and update it as shown below.

<?php

namespace App\\Http\\Controllers;

use Illuminate\\Http\\Request;
use Mail;
use App\\Mail\\SendMail;

class EmailController extends Controller
{
    public function index()
    {
        $testMailData = [
            'title' => 'Test Email From AllPHPTricks.com',
            'body' => 'This is the body of test email.'
        ];

        Mail::to('[email protected]')->send(new SendMail($testMailData));

        dd('Success! Email has been sent successfully.');
    }
}

Now create an email directory in the resources/views folder and then build a testMail.blade.php blade view file here. Paste the following code into it.

<!DOCTYPE html>
<html>
<head>
    <title>AllPHPTricks.com</title>
</head>
<body>
    <h1>{{ $testMailData['title'] }}</h1>
    <p>{{ $testMailData['body'] }}</p>
</body>
</html>

The next step creates a web route that will send testing emails, and I will add the following code to the routes/web.php file.

<?php

use Illuminate\\Support\\Facades\\Route;
use App\\Http\\Controllers\\EmailController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here you can register web routes for your application. 
These routes are loaded by the RouteServiceProvider into a group 
that contains the "web" middleware group.
|
*/

Route::get('/send-email', [EmailController::class, 'index']);

So, we finished all the necessary steps to make an email using Laravel 9 and Gmail SMTP. It’s time to start the development server and test the application now.

Run the given command to run the development server.

php artisan serve

Open the browser and click on the following URL to send an email using SMTP from Laravel 9.

<http://localhost:8000/send-email>

Integrate Mailtrap with Laravel

Paste the following code to create a mail route.

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

You just have to type in your credentials in Mailtrap’s default Laravel server.

The .env file is sufficient for the majority of cases. Alternatively, you can set your config/mail.php file to the following content:

<?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"
];

Follow the given command to make a Mailable class on SSH terminal.

php artisan make:mail MailtrapExample

To begin, you must locate the Mail directory in the app/Mail. Since you have a template with predefined functions, you can alter it using the following code:

<?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>'
           ]);
   }

Now, you must develop a ’emails’ directory with a blade template file ’emailexample.blade.php’ in the blade.php file. In this case, the mailable class is defined in the mails.exmpl.

Paste the code below to create a mail route.

<?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!';
 
})

Summary

This brings us to the end of this article, which demonstrates in detail the complete guide to sending emails in Laravel.

In addition, we considered the integration process of various emailing tools in Laravel. We learned how to send emails from your Laravel web app using SMTP.

Using these pre-built tools, you can quickly send emails in a Laravel application. And your developers can get started with email tools shortly, as their integration process is easy.