Send email in Laravel using Gmail SMTP

Sometimes we needs to send email from our local server or localhost, the simplest way we can do to send emails through localhost is using our Gmail account as SMTP server.

Follow the steps below:

Step 1: Update SMTP configuration in .env file.

The default configuration is :

MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null

Edit the details above as follows :

MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=465
MAIL_USERNAME=ENTER_YOUR_GMAIL_ADDRESS
MAIL_PASSWORD=ENTER_YOUR_GMAIL_PASSWORD
MAIL_ENCRYPTION=ssl

In the above settings, we configured MAIL_DRIVER as smtp, MAIL_HOST for Gmail as smtp.googlemail.comMAIL_ PORT for Gmail as 465 and MAIL_ENCRYPTION method as ssl.

Since we are using Gmail SMTP, we need to change some security settings on our Google account, to give access to less secured applications.

Step 2: Configure our Google Account

Login to Google Email Account and click on “Manage your Google Account” button. This button is display when you click on the profile picture in your Gmail Dashboard as shown.

Once we are on our “My Account Page” then click on Security and scroll down to the bottom and you will find “Less secure app access” settings. Click on the radio button to set it ON.

Step 3: Testing send email from Laravel

At this point, all the basic setup has been completed. We can now test it simpy using Laravel tinker.

First, create blade template “emails.mail” hence we need to create an ’emails’ folder and the mail.blade.php file atresources\views\emails\mail.blade.php

Our test mail template mail.blade.php should just contains a few test codes as shown below.

Hello Lorem ipsum dolor sit amet

And then, open Tinker console.

php artisan tinker

Write this command in the console (after the >>>):

Mail::send('emails.mail', [], function ($message) { 
    $message->to('[email protected]')
     ->subject('Tes Gmail SMTP Sender Email!'); 
});

Tinker will return null value, if email successfully sent. Or return error if its failed.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>