How to send email using gmail in PHP Laravel 5?



Laravel is a very popular framework for PHP in today's. Laravel is famous because they provide several goods things like MVC, routing, mail etc. In this article, we will learn how to send email using SMTP driver. Laravel 5 provide several drivers options like SMTP, Mail, SendMail, and services supported include Mailgun, Sendgrid, Mandrill, Amazon SES, etc.
So, here i will let you know how to send email from your Gmail account using SMTP driver. Laravel provides the configuration file for email. you can see that file here: config/mail.php, you can also make the change manually but laravel is smart so they provide .env file for configuration as like below:
.env
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=addYourEmail
MAIL_PASSWORD=AddYourEmailPassword
MAIL_ENCRYPTION=tls
You can simply configuration here as above env variable. now I am going to provide a simple example to add a new route to your route file as like bellow added.
routes/web.php
Route::get('send-main', 'HomeController@sendMail');
Next, i will add new sendMail() in HomeController like as bellow I added, here in this method we write code or send an email with the title. So let's see bellow controller method.
Controller Method:
public function sendMail()
{
    $data['title'] = "Hii welcome to my blog";
    Mail::send('emails.email', $data, function($message) {
        $message->to(‘deepak@gmail.com', 'Receiver Name')
                ->subject('laravelarticels.com Mail');
    });
    dd("Mail Sent successfully");
}
At Last, we need to create email blade file in emails folder of view. So if you have't created "emails" folder then create and create new email.blade.php file, put bellow code:
if you find any error about gmail less secure then click this bellow link and turn on the Allows  less secure app
resources/views/emails/email.blade.php

<h1>{{ $title }}</h1>
<p>Thank you</p>

Comments

Popular posts from this blog

Laravel 5 Chart example using Charts Package

PHPMyBackup - A PHP MySQL differential backup script

Laravel Stats Tracker