How to Send Email using PHPMailer in Laravel 9

PHPMailer : PHPMailer is a code library to send emails safely and easily via PHP code from a web server. Sending emails directly by PHP code requires a high-level familiarity to SMTP protocol standards and related issues and vulnerabilities about Email injection for spamming. 

Today, I am going to show you how you can send email using PHPMailer in laravel 9. Most of the developers out there will suggest you to use SMTP Server to send mail.

Also Read : Laravel 9 – Drag and Drop file upload using Dropzone

How to Send Email using PHPMailer in Laravel 9

  • Step 1 : Install PHPMailer into Laravel 9
  • Step 2 : Create a Controller
  • Step 3 : Create Routes
  • Step 4 : Create Views
  • Step 5 : GMAIL SMTP
  • Step 6 : Conclusion

Step 1 : Install PHPMailer into Laravel 9

First, We are going to install PHPMailer to our laravel 9 application using composer. To install the PHPMailer open the command prompt and enter the the following command:

composer require phpmailer/phpmailer 

To see if the PHPMailer package has been installed, open the composer.json file, which is located at the root of the project.

Step 2 : Create a Controller

After successfully installing PHPMailer. Now we are going to create a controller with a name PHPMailerController.php

To create a controller we need to run a command:

php artisan make:controller PHPMailerController

Now at very first, Load the PHPMailer and Exception classes to configure the PHPMailer SMTP.

use PHPMailer\PHPMailer\PHPMailer;  
use PHPMailer\PHPMailer\Exception;

Open the Controller file which we had just create from app/Http/Controllers there you will find PHPMailerController.php and add the following code to the controller.

Also Read : How to install Selectize.JS in Laravel 9

<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
 
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
 
class PHPMailerController extends Controller {
 
    // =============== [ Email ] ===================
    public function email() {
        return view("email");
    }
 
 
    // ========== [ Compose Email ] ================
    public function composeEmail(Request $request) {
        require base_path("vendor/autoload.php");
        $mail = new PHPMailer(true);     // Passing `true` enables exceptions
 
        try {
 
            // Email server settings
            $mail->SMTPDebug = 0;
            $mail->isSMTP();
            $mail->Host = 'smtp.example.com';             //  smtp host
            $mail->SMTPAuth = true;
            $mail->Username = 'user@example.com';   //  sender username
            $mail->Password = '**********';       // sender password
            $mail->SMTPSecure = 'tls';                  // encryption - ssl/tls
            $mail->Port = 587;                          // port - 587/465
 
            $mail->setFrom('sender@example.com', 'SenderName');
            $mail->addAddress($request->emailRecipient);
            $mail->addCC($request->emailCc);
            $mail->addBCC($request->emailBcc);
 
            $mail->addReplyTo('sender@example.com', 'SenderReplyName');
 
            if(isset($_FILES['emailAttachments'])) {
                for ($i=0; $i < count($_FILES['emailAttachments']['tmp_name']); $i++) {
                    $mail->addAttachment($_FILES['emailAttachments']['tmp_name'][$i], $_FILES['emailAttachments']['name'][$i]);
                }
            }
 
 
            $mail->isHTML(true);                // Set email content format to HTML
 
            $mail->Subject = $request->emailSubject;
            $mail->Body    = $request->emailBody;
 
            // $mail->AltBody = plain text version of email body;
 
            if( !$mail->send() ) {
                return back()->with("failed", "Email not sent.")->withErrors($mail->ErrorInfo);
            }
            
            else {
                return back()->with("success", "Email has been sent.");
            }
 
        } catch (Exception $e) {
             return back()->with('error','Message could not be sent.');
        }
    }
}

Please don’t forgot to change the SMTP Details like as username, password, sender email, sender name to send an email using your own credentials.

Step 4 : Create Views

Now we are going to create some route for our application. To create a routes we have to open routes/web.php file.

And add the following code to the file.

<?php
 
use App\Http\Controllers\PHPMailerController;
use Illuminate\Support\Facades\Route;
 
Route::get("email", [PHPMailerController::class, "email"])->name("email");
 
Route::post("send-email", [PHPMailerController::class, "composeEmail"])->name("send-email");

Now the routes has been created. We are going to create Views.

Also Read : Laravel 9 OrderBy ASC and DESC Tutorial

Step 4 : Create Views

We are going to create a view file in resources/views with the name email.blade.php

Just add the following code to the blade templated which we just created.

<!doctype html>
<html lang="en">
  <head>
    <title>How to Send Email using PHPMailer in Laravel 9 - LaravelTuts.com</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  </head>
  <body>
      <div class="container pt-5 pb-5">
        <div class="row">
            <div class="col-xl-6 col-lg-6 col-sm-12 col-12 m-auto">
                <form action="{{route('send-email')}}" method="POST" enctype="multipart/form-data">
                    @csrf
                    <div class="card shadow">
 
                        @if(Session::has("success"))
                            <div class="alert alert-success alert-dismissible"><button type="button" class="close">&times;</button>{{Session::get('success')}}</div>
                        @elseif(Session::has("failed"))
                            <div class="alert alert-danger alert-dismissible"><button type="button" class="close">&times;</button>{{Session::get('failed')}}</div>
                        @endif
 
                        <div class="card-header">
                            <h4 class="card-title">Send Email Using PHPMailer</h4>
                        </div>
 
                        <div class="card-body">
                            <div class="form-group">
                                <label for="emailRecipient">Email To </label>
                                <input type="email" name="emailRecipient" id="emailRecipient" class="form-control" placeholder="Mail To">
                            </div>
 
                            <div class="form-group">
                                <label for="emailCc">CC </label>
                                <input type="email" name="emailCc" id="emailCc" class="form-control" placeholder="Mail CC">
                            </div>
 
                            <div class="form-group">
                                <label for="emailBcc">BCC </label>
                                <input type="email" name="emailBcc" id="emailBcc" class="form-control" placeholder="Mail BCC">
                            </div>
 
                            <div class="form-group">
                                <label for="emailSubject">Subject </label>
                                <input type="text" name="emailSubject" id="emailSubject" class="form-control" placeholder="Mail Subject">
                            </div>
 
                            <div class="form-group">
                                <label for="emailBody">Message </label>
                                <textarea name="emailBody" id="emailBody" class="form-control" placeholder="Mail Body"></textarea>
                            </div>
 
                            <div class="form-group">
                                <label for="emailAttachments">Attachment(s) </label>
                                <input type="file" name="emailAttachments[]" multiple="multiple" id="emailAttachments" class="form-control">
                            </div>
                        </div>
 
                        <div class="card-footer">
                            <button type="submit" class="btn btn-success">Send Email </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
      </div>
      
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
  </body>
</html>

Now just save the file.

Preview of our blade file :

After filling the form data and submitting the success message will be shown that email has been sent!

Also Read : Laravel 9 Shopping Cart Tutorial with Ajax Example

Step 5 : GMAIL SMTP

If you like to send email using Gmail SMTP server in Laravel 9. To use Gmail SMTP with the PHPMailer library in Laravel, you must be changed some settings in the Google account. Please follow the below steps.

Step One, Open your google account and navigated to you My Account page.

Step Two, On left end side you will find Security. Scroll Down till you find Signing into Google section then Turn Off the 2-Step Verification.

google account security 2 step verification gmail smtp 840x310 1

Step Three, now click Less secure app access section and turn On Less secure app access.

google account security less secure app access gmail smtp 840x273 1

That its, Now you are ready to send mail using Gmail SMTP server into laravel 9 application.

Update your Gmail account credentials (email address and password) in the below code snippet

// SMTP configuration 
$mail-&gt;isSMTP(); 
$mail-&gt;Host     = 'smtp.gmail.com'; 
$mail-&gt;SMTPAuth = true; 
$mail-&gt;Username = 'sender@gmail.com'; 
$mail-&gt;Password = '******'; 
$mail-&gt;SMTPSecure = 'tls'; 
$mail-&gt;Port     = 587;

Now you are ready to send email using Gmail SMTP in Laravel.

Step 6 : Conclusion

In this tutorial you have learn How to Send Email using PHPMailer in Laravel 9. You can extend the functionality as per your requirement. I hope you found this tutorial helpful for your project. Keep learning!.

If you have any trouble with the tutorial you can ask me via the comment section below. Thank You!

Also Read : How to Install Alpine.js in Laravel 9

4 Comments

Leave a Reply