Vaidikalaya

Send mail using Gmail in Laravel


To send mail in Laravel using Gmail, you'll need to set up your Laravel application to use Gmail's SMTP server. Here's a step-by-step guide to help you do that:


STEP 1: Configure your Gmail Account

When using Gmail SMTP the first step is to configure your Gmail account for sending mail. So follow the provided steps and do some settings in your Gmail account.

1. Open your Gmail account and Enable two-step verification and generate a password


  • Now click on security and go to the security page.

  • Now scroll down and on 2 step verification

  • Now click on get started button and complete further process for opening two step verification

  • After two step verification, Again click on 2 step verification link for setting up password.

  • When come 2 step verification screen, scroll down and come in password section.

  • Now click on app password and generate a password for app.

  • Now fill app name and click on create button, It will generate a password for this app.

  • Now copy this password and save it for further use. Because this password is use in .env file for authentication.

Step 1 (configuration of gmail account) is completed. Save the above password for further authentication process.


Step 2: Create Laravel App

Create Laravel app by running this command in your terminal:

laravel new send-mail-using-gmail-smtp

OR

composer create-project laravel/laravel send-mail-using-gmail-smtp

Now go to the project directory

cd send-mail-using-gmail-smtp   

Step 3: Now create a blade file for writing mail

Create a new Blade view file or change an existing file (welcome.blade.php) for writing emails in the resources/views/ directory. For example, resources/views/welcome.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Laravel Gmail SMTP</title>

    <!--Bootstrap-->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
   
    <div class="container mt-5">
        <div class="card w-50">
            <div class="card-header">
                Send Mail
                @if(session('success'))
                    <span class="text-success">{{session('success')}}</span>
                @endif
            </div>
            <div class="card-body">
                <form action="{{route('send-mail')}}" method="POST">
                    @csrf
                    <div class="mb-3">
                        <label for="email" class="form-label">Email</label>
                        <input type="email" name="email" class="form-control" id="email" placeholder="email">
                        @error('email') <span class="text-danger">{{$message}}</span> @enderror
                    </div>
                    <div class="mb-3">
                        <label for="message" class="form-label">Messagelabel>
                        <textarea name="message" class="form-control" id="message" rows="3"></textarea>
                        @error('message') <span class="text-danger">{{$message}}span> @enderror
                    </div>
                    <div class="float-end">
                        <button class="btn btn-primary">Send</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

</body>
</html>


This will create a view template where you can fill email ID and message then click on the send button it will fire a backend query and send a mail to the filled email ID with the attached message. The view template looks like this:


Step 4: Create Mail Class

Generate a new Mailable class using Artisan

php artisan make:mail TestMail
This will create a new file in the app/Mail directory. Open it and define the email content and structure:

App\Mail\TestMail.php

namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;

class TestMail extends Mailable
{
    use Queueable, SerializesModels;

    public $msg;
    public function __construct($message)
    {
        $this->msg=$message;
    }

    /*
        Here you can define mail subject,
        from address and reply to address
    */
    public function envelope(): Envelope
    {
        return new Envelope(
            subject: 'Test Mail',
        );
    }

     /*
        Here you define view blade file
        which is used for email template
    */
    public function content(): Content
    {
        return new Content(
            view: 'emails.test-email',
        );
    }


    public function attachments(): array
    {
        return [];
    }
}


Change your Mail Class according to you with the reference of the above file


Step 5: Create Email blade file

We are creating this blade file because when mail is fired then it will use a template file which is defined within the content method of the TestMail class. This blade file can use all dynamic data that is passed through the TestMail class.

So create a new blade file for your email template in the resources/views/emails directory and define it in the content method of the TestMail class. For example, resources/views/emails/test-email.blade.php:

This view will be used for the email template. 

<h3>Hi, Dearh3>
<p>
    {{$msg}}
p>
<p>
    Regards,
    <br>
    Test Mail
p>

Step 6: Create the controller

Create a new Controller class using Artisan:

php artisan make:controller HomeController
Write the code for receiving data from the request and send the mail to the requested email id.

1. Write the validation for the requested data.

2. Import Mail facade and TestMail class.

3. Now fire the mail using the Mail facade and TestMail class.

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Mail\TestMail;

class HomeController extends Controller
{
    public function sendMail(Request $request){
        $request->validate([
            'email'=>'required',
            'message'=>'required'
        ]);

        Mail::to($request->email)->send(new TestMail($request->message));

        return back()->with('success','Mail Send Successfully');
    }
}

Step 7: Create routes

Now go to the routes/web.php file and define the post route for the send mail

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HomeController;

Route::get('/', function () {
    return view('welcome');
});

Route::post('/send-mail',[HomeController::class,'sendMail'])->name('send-mail');

Step 8: Configure the .env file

Open the .env file and configure your mail settings:

Set your Gmail address in the MAIL_USERNAME field and the password which was generated using 2-factor authentication that password will be used in the MAIL_PASSWORD field.  

MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=vtest3024 #your gmail address
MAIL_PASSWORD="inbi mfak ccrb dity" #password - generated by 2-factor authentication
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS="vtest3024@gmail.com"
MAIL_FROM_NAME="${APP_NAME}"



Step 9: Now run and test the app

Run the app using the artisan command

php artisan serve

Now open your browser and test the app

Output


Test Case 1: Send without filling data


Test Case 2: Now fill correct data