Laravel Send Email SMTP Using Gmail and Mailtrap

laravel send email, laravel 5.8 pdf generator, laravel send email gmail, laravel 5.8 gmail smtp

Laravel send email example will guide you to send email from Gmail and Mailtrap SMTP.

Table of Content

1. Laravel Send Email SMTP Using Gmail

2. Laravel Send Email Example | Email SMTP | Mailtrap

1. Laravel Send Email SMTP Using Gmail

Laravel Send Email Gmail Example is today’s core concept.

In this tutorial, you will learn how to send email via Gmail SMTP from any laravel web site.

Gmail smtp works as a mediator between the laravel web site and receiver email address.

Many cases like invoice generation, food order summary etc. things are required to be mailed to the respective user. Here, this example will help you to send emails in no time.

First of all, check the below video to see the output.

Step 1. Complete New Project

Our first work is to make a new fresh laravel project. For this, run the below command in terminal window

laravel new laraemailgmail

Above line will make a new laravel project and it will set the name of the project as “laraemailgmail

Step 2. Configuration of .env

We are going to use gmail as a SMTP in this example. For this, we need to do some settings in .env file.

So open up your laravel project’s .env file and see the below lines.

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

By default, laravel is using mailtrap as a SMTP and 2525 as a port number.

We need to change above configuration lines. So, try to change above lines with below code

MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=465
MAIL_USERNAME=something@gmail.com
MAIL_PASSWORD=gmailPassword
MAIL_ENCRYPTION=ssl

You just need to add your gmail address as an username and add your gmail’s password as a password.

Note : Add the gmail address and password of the sender in the above lines.

Step 3. Allow Less Secure

Now we need to do one special thing. We should allow the less secure app access in the sender’s email address. ( An email address which we have added in the .env file )

First of all, see the below image

laravel send email gmail

Now click on the Google Account button. It will open the screen like the following image

laravel send email gmail

Above image is of the left menu bar. Here, click on the Security tab and you will see the following picture

You need to scroll down the page to reach at the following screen. Now select “Turn on access” and it will redirect you to following screen

You can see there is one switch is there. Just turn on this switch and your work is done.

Step 4. Making One Route

Now go to routes->web.php file and add the following line in it

Route::get('sendgmail', 'SendGmailController@sendgmail');

This line is simply defining one route. When the user runs http://127.0.0.1:8000/sendgmail URL in the browser, compiler will execute the sendgmail() function from SendGmailController.php file, which is a controller file.

Step 5. Writing Controller

Now it is time to create one controller file. For this, execute the following command in your cmd window

php artisan make:controller SendGmailController

After this, navigate to app->Http->Controller directory. Here, you will find a file with the name SendGmailController.php

Open this file and add the below source snippet

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Mail;

class SendGmailController extends Controller
{
    //
    public function sendgmail()
    {
        $data = array('name'=>"Sam Jose", "body" => "Test mail");
    
        Mail::send('gmailview', $data, function($message) {
            $message->to('johndoesense12@gmail.com', 'John Doe')
            ->subject('From Laravel With Gmail');
            $message->from('jesalmithani15@gmail.com',' Jesal Mithani');

          });

          if (Mail::failures()) {
            return response()->Fail('Sorry! Please try again latter');
          }else{
            return response()->json('Yes, You have sent email to GMAIL from LARAVEL !!');
          }
   }
}

Now let us understand the above code in detail.

First of all, see the below snippet

 Mail::send('gmailview', $data, function($message) {
            $message->to('johndoesense12@gmail.com', 'John Doe')
            ->subject('From Laravel With Gmail');
            $message->from('jesalmithani15@gmail.com',' Jesal Mithani');

          });

See the first line in above code, it is referencing to the blade view file gmailview.blade.php We will create this view file in the next step.

Second line is defining the email address of the receiver. You need to add receiver’s email address in the first parameter.

In the second parameter, you can write the name of the recipient.

Third line is defining the subject of the email. You can add anything here.

Final line is writing the email address and name of the sender.

Now focus on the below source snippet

if (Mail::failures()) {
            return response()->Fail('Sorry! Please try again latter');
          }else{
            return response()->json('Yes, You have sent email to GMAIL from LARAVEL !!');
          }

There is one if condition is there. It is checking if the email is successfully sent or not. If yes, then the if condition will be false and system will print the message like “Yes, You have sent email to GMAIL from LARAVEL !!”

and if the email is not sent then the if condition will be true and system will write the message like “Sorry! Please try again latter”

Step 6. Last View File

This is our last step. We just need to create one blade view file to finish this example.

So navigate to resources->views directory and make a new file named gmailview.blade.php

write down the below source code lines in gmailview.blade.php

<!DOCTYPE html>
<html>
<style>
body {font-family: Arial, Helvetica, sans-serif;}
 
form {
  border: 3px solid #f1f1f1;
  font-family: Arial;
}
 
.container {
  padding: 20px;
  background-color: #f1f1f1;
}
 
input[type=text], input[type=submit] {
  width: 100%;
  padding: 12px;
  margin: 8px 0;
  display: inline-block;
  border: 1px solid #ccc;
  box-sizing: border-box;
}
 
input[type=checkbox] {
  margin-top: 16px;
}
 
input[type=submit] {
  background-color: #4CAF50;
  color: white;
  border: none;
}
 
input[type=submit]:hover {
  opacity: 0.8;
}
</style>
<body>
 
<h2>CSS Newsletter</h2>
 
<form >
  <div class="container">
    <h2>Subscribe to our Newsletter</h2>
    <p>Click the below button to subscribe.</p>
  </div>
 
  <div class="container" style="background-color:white">
    <input type="text" placeholder="Name" name="name" required>
    <input type="text" placeholder="Email address" name="mail" required>
    <label>
      <input type="checkbox" checked="checked" name="subscribe"> Daily Newsletter
    </label>
  </div>
 
  <div class="container">
    <input type="submit" value="Subscribe">
  </div>
</form>
 
</body>
</html>

This view file contains the HTML code. It is creating a look and feel for our email.

System will use this file to create the view of our Email.





2. Laravel Send Email Using MailTrap SMTP

Welcome to Laravel Send Email Example Tutorial. We will learn how to send emails from any laravel web site to any email id in this article.

We are using SMTP to send email from the laravel project. Mailtrap will help us to test the sent email.

In many cases like, sending invoice or quotation, we need to send email to the user. Here, this tutorial will help you to send this type of email from laravel web site.

I will also teach you how you can make a custom view ( look and feel ) for emails. We do this by creating separate blade view files for emails.

First of all, checkout the below output video from youtube.

Follow all the below steps to create laravel send email example.

Step 1. Basic Task

Our first task is to make a new laravel project. For this, run the below command in your cmd

laravel new larasendemail

This command will create a new project and it’s name would be “larasendemail

Step 2. Configuring .env for SMTP

To enable testing with emails, we will use mailtrap testing environment.

First of all, go to https://mailtrap.io and create new account if you have not any.

On the dashboard, you will see some configuration details like username, password, port etc. We need to add them in our laravel project.

Once, you have successful account on mailtrap, open your laravel project in editor like sublime or visual studio code.

Now open your .env file and see the below source code.

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

Just add username and password as per your mailtrap dashboard and you are done with .env file.

Step 2. Writing Route File and Controller

Now go to routes->web.php file. Write the below line in this file.

Route::get('sendemail', 'SendEmailController@sendmail');

When the user runs the URL http://127.0.0.1:8000/sendemail in the web browser, system will call sendmail() function from SendEmailController.php file.

Now let us create controller file. For this, trigger the following command in cmd

php artisan make:controller SendEmailController

This command will make a new controller file inside app->Http->Controller directory. Here, you should find the file named SendEmailController.php file.

Open this SendEmailController.php file and add the following source snippet in it

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Mail;

class SendEmailController extends Controller
{
    //
    public function sendmail()
    {
        $data['title'] = "Laravel Send Email From Mail trap";
 
        Mail::send('mailview', $data, function($message) {
 
            $message->to('johndoesense12@gmail.com', 'Receiver Name')
 
                    ->subject('Laravel Send Email');
        });
 
        if (Mail::failures()) {
           return response()->Fail('Sorry! Please try again latter');
         }else{
           return response()->json('Yes, You have sent email from LARAVEL !!');
         }
    }
}

Look inside the sendmail() function.

First line is setting the title of the email.

Second line will set the view file for the email. Here, it is “mailview” means that a file named mailview.blade.php will be used to create the look and feel of the email. We will create this file in the next step.

Concentrate on below lines

 $message->to('johndoesense12@gmail.com', 'Receiver Name')
 
                    ->subject('Laravel Send Email');

First line is the value of the email id where we want to send the email. Second line is allowing us to write the subject of the email.

Now see the following snippet

 if (Mail::failures()) {
           return response()->Fail('Sorry! Please try again latter');
         }else{
           return response()->json('Yes, You have sent email from LARAVEL !!');
         }

One if else loop is there. Compiler will run the above lines when system have tried to send the email. If email is not sent successfully then the if loop will be true and it will print the message like “Sorry! Please try again latter

If system has achieved success in sending email, compiler will print the line like “Yes, You have sent email from LARAVEL !!

Step 3. Blade File for Email

Now let us make a view file for email. Go to resources->views directory and create a new file and give it a name like mailview.blade.php

Write down the below source code snippet in mailview.blade.php file.

<!DOCTYPE html>
<html>
<style>
body {font-family: Arial, Helvetica, sans-serif;}

form {
  border: 3px solid #f1f1f1;
  font-family: Arial;
}

.container {
  padding: 20px;
  background-color: #f1f1f1;
}

input[type=text], input[type=submit] {
  width: 100%;
  padding: 12px;
  margin: 8px 0;
  display: inline-block;
  border: 1px solid #ccc;
  box-sizing: border-box;
}

input[type=checkbox] {
  margin-top: 16px;
}

input[type=submit] {
  background-color: #4CAF50;
  color: white;
  border: none;
}

input[type=submit]:hover {
  opacity: 0.8;
}
</style>
<body>

<h2>CSS Newsletter</h2>

<form >
  <div class="container">
    <h2>Subscribe to our Newsletter</h2>
    <p>Click the below button to subscribe.</p>
  </div>

  <div class="container" style="background-color:white">
    <input type="text" placeholder="Name" name="name" required>
    <input type="text" placeholder="Email address" name="mail" required>
    <label>
      <input type="checkbox" checked="checked" name="subscribe"> Daily Newsletter
    </label>
  </div>

  <div class="container">
    <input type="submit" value="Subscribe">
  </div>
</form>

</body>
</html>

Here, you can add any html code to generate your own email custom view.