How to Send Emails Directly from a Laravel Controller

How to Send Mail Directly from Controller in Laravel


If you want to send Mail directly from controller without using any Laravel Notification and any other method then this article is for you . In this article we will learn how to send Mail directly from Controller .

It's super easy to send a Mail from controller and we will see how to attach your view file with your Mail , you just need to write some lines of code and that's it . Let's see step by step how to send mail directly from controller in laravel 7 .


Step 1 - Setup Mail Configuration :

First set up you ' .env ' file with your mail configuration for now i will be using Mailtrap for sending mail . Make your Mail configuration in your .env file as shown below .



MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=34d7af640c9818 //mail username
MAIL_PASSWORD=d07708a6993e38 //mail password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=0e3aa00606-f48da0@inbox.mailtrap.io //sender mail address
MAIL_FROM_NAME="${APP_NAME}"


Step 2 - Create Route :

Setup your Route in your web.php .

Route::get('/sendmail','SendMailController@sendmail');


Step 3 - Make a Controller :

If you already have your controller then you don't to create again , otherwise use the following command to create a controller .


php artisan make:controller SendMailController


Step 4 - Code for Sending Mail :

Syntax for Send Mail :


Mail::send('view-file-name', $arraywithuserdetail, function($message)use($arraywithuserdetail)
{
   $message->to($arraywithuserdetail["email"], $arraywithuserdetail["client_name"])
   ->subject($arraywithuserdetail["subject"]);
});

Use the following class on your controller in order to use Mail


use Illuminate\Support\Facades\Mail;


Step 5 - Setup Your Controller :

SendMailController.php :


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
class SendMailController extends Controller
{
    public function sendmail()
    {

     /*
   Your any other logic goes here 
     */


  //Settingup the credentials for sending mail

  $userdetail["email"]='studywithkishan@gmail.com';
  $userdetail["client_name"]='studywithkishan';
  $userdetail["subject"]='Welcome Mail';

  //Code for sending the mail to the corresponding user

  Mail::send('welcomemail', $userdetail, function($message)use($userdetail) {
   $message->to($userdetail["email"], $userdetail["client_name"])
   ->subject($userdetail["subject"]);
  });

  return 'mail sent successfully';

    }
}


Step 6 - Setup View file :

welcomemail.blade.php :


<!DOCTYPE html>
<html>
   <head>
      <title>Mail View File</title>
   </head>
   <body>
      <h1>This is the view file</h1>
   </body>
</html>
Previous Post Next Post

Contact Form