Laravel and PHPMailer source code for sending email

Laravel by default uses swift mailer. If in some case you are getting issue while using swift mailer, In this case you can use PHPMailer.

In Laravel 5.4 or Above, you need to do the following steps

Install the PHPMailer on your laravel Application.

After going to your project folder from the CLI, you need to run below command from the CLI. Below command will install the phpmailer library in your laravel project.

composer require phpmailer/phpmailer

The next thing we need to do is to create our controller php file that will handle the send email functionality.

php artisan make:controller PHPMailerController

Open your PHPMailerController.php file located at your-project-folder/app/Http/Controllers/and paste the source code below.

<?php
namespace App\Http\Controllers;

use PHPMailer\PHPMailer;

class PHPMailerController extends Controller
{
   public function index()
   {
       require 'vendor/autoload.php'; // load Composer's autoloader
       $mail = new PHPMailer\PHPMailer(true); // Passing `true` enables exceptions

       try
       {
            $mail->isSMTP(); // Set mailer to use SMTP
            $mail->Host = 'server-host'; // Specify main and backup SMTP servers
            $mail->SMTPAuth = true; // Enable SMTP authentication
            $mail->Username = 'server-email@example.com'; // SMTP username
            $mail->Password = 'server-paasword'; // SMTP password
            $mail->SMTPSecure = 'TLS'; // Enable TLS encryption, `ssl` also accepted
            $mail->Port = 587; // server port
            //Recipients
            $mail->setFrom('server-email@example.com', 'name');
            $mail->addAddress("receiver-email@example.com");
            $mail->isHTML(true); // Set email format to HTML
            $mail->Subject = "your subject";
            $mail->Body = "test body";
            $mail->send();
         }
         catch (Exception $e)
         {
             echo "<pre>";print_r($e);
         }
         exit();
     }
}
?>

Next step is, Open your web.php file located at your-project-folder/routes/ and paste the source code below.

Route::get('/send_mail', 'PHPMailerController@index');

For execute above code, you need to hit below URL.

http://domain-name/your-project-folder/send_mail

 

You may also like

Leave a Reply