Hello readers!!! What's up? Today I'm here with you with a tutorial based on Sending Emails using Laravel. Actually I will send this via localhost! I have tried many times to do this before starting using Laravel.. I must say this is the simplest way I found to send mails through localhost using gmail. That's why I'm still saying this is a fantastic PHP framework! Now we can start our work..

Get complete project from GitHub : Laravel Emails

Step 1 -  Create a new Laravel project

composer create-project laravel/laravel LaravelMail

Step 2 -  Create the front view

We need to create the front view to input an email to send the mail. I use Bootstrap 4 for styling the web pages.

resources/view/welcome.blade.php
<!doctype html>
<html lang="{{ app()->getLocale() }}">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Laravel</title>
        <!-- Bootstrap core CSS -->
        <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">
        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css">
    </head>
    <body>
        <div class="container" style="margin-top: 100px; width: 600px;">
            <h2 class="text-center">Send Emails in Laravel via Localhost</h2><br><br>
            @if(session('success'))
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                        {{session('success')}}
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            @endif
            @if(count($errors)>0)
                @foreach($errors->all() as $error)
                    <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            {{$error}}
                        <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                @endforeach
            @endif
            <form action="send" method="POST">
                {{ csrf_field() }}
                <div class="form-group">
                    <input type="email" class="form-control text-center" placeholder="Provide an email" name="email"><br>
                    <button type="submit" class="btn btn-primary btn-md" style="margin-left: 0px;margin: auto; display: block;"t>SEND</button>
                </div>
            </form>
        </div>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <!-- Bootstrap core JavaScript -->
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/js/bootstrap.min.js"></script>
    </body>
</html>


Step 3 -  Make routes

routes/web.php
Route::get('/', function () {
    return view('welcome');
});

Route::post('send', 'MailController@send');



Step 4 -  Update .env file

This is the most important part. We need to give some credentials correctly here... Open .env file and place go to MAIL settings.

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=your_gmail_used_to_send_emails@gmail.com
MAIL_PASSWORD=your_email_password
MAIL_ENCRYPTION=tls


Step 5 -  Give the right to send mails via localhost to your email

Under the usual Gmail settings, you will not be able to send mails! SO, you have to do a small additional configuration in your gmail provided in the env file. Sign into the gmail acount you gave in env file.

1. Go to My Account and then Sign-in & Security.


2. Find the option below in the page - Allow less secure apps.. Turn it ON..

Step 6 -  Create a Mail Class and configure it

Open cmd and type the below command to create a Mail class to configure mails.

php artisan make:mail SendMail

Now you will have a new class file in the app folder within a Mail folder. Open it and place this code..

<?php

namespace App\Mail;

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

class SendMail extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        // mail is the view..
        return $this->view('mail')->subject('Test Mail');
    }
}

Here, subject is the Title for your mail..In Gmail you will see it like this..


Step 7 -  Create the Email file called - mail.blade.php

resources/views/mail.blade.php

<!DOCTYPE html>
<html>
<head>
 <title>Test Mail</title>
</head>
<body>
 <p>This is the mail you get from me.</p>
</body>
</html>

Step 8 - Create a controller to handle the form and send mails

php artisan make:controller MailController

app/Http/Controllers/MailController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Mail\SendMail;
use Illuminate\Support\Facades\Input;

class MailController extends Controller
{
    public function send(Request $request)
    {
        $this->validate($request, [
            'email' => 'required'
        ]);
     Mail::to($request->input('email'))->send(new SendMail());
     return redirect()->back()->with('success', 'Email sent successfully. Check your email.');
    }
}

Step 9 - Edit mail config file

There's a file called mail.php in config folder. Open it and do this change.
    'from' => [
        'address' => env('MAIL_FROM_ADDRESS', 'your_sender_mail'),
        'name' => env('MAIL_FROM_NAME', 'your_sender_name'),
    ]

Step 10 - You are ready to send emails now.. 

Open your web cmd and type php artisan serve.Then open web browser and type localhost:8000.Provide a valid email and click on send button. Check the mail entered and there you will see a new mail from the sender you have given..





6 Comments

  1. ExpressTech Software Solutions is a Laravel Development Company, we are having a group of master Dedicated Laravel Developers with great Laravel Experience. Contact us to find more about laravel software. Contact@ExpressTechSoftwares.Com or +91-9806724185

    ReplyDelete
  2. the mail is mentioned as mail.blade.php but i cant use php statements in it What may be the reason?

    ReplyDelete
    Replies
    1. You should put your php statements inside the php tag like this:

      Delete