How to Send Mail using Gmail SMTP Server with Laravel 8
Laravel 8 Send Mail using Gmail SMTP Server
In this tutorial, I will provide an example of how to send emails using Gmail SMTP in Laravel 8. It's a straightforward example of how to send emails in Laravel 8 using Google Gmail. This post offers a simple example of how to send emails using Gmail SMTP in Laravel 8.
To send emails using Gmail in Laravel 8, you just need to follow a few steps. In this tutorial, I will provide a step-by-step guide to sending emails using the Google Gmail SMTP server in Laravel 8. You can create a blade file design with dynamic information for your mail layout. So, let's get started with the step-by-step guide and send emails as per your requirement.
Step 1: Make Configuration
The first step involves configuring the mail driver as a Gmail server and providing the necessary details such as mail host, mail port, mail username, and mail password. This will enable Laravel 8 to use these details while sending the email. The following code can be used to achieve this.
.env
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=mygoogle@gmail.com
MAIL_PASSWORD=rrnnucvnqlbsl
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=mygoogle@gmail.com
MAIL_FROM_NAME="${APP_NAME}"
Step 2: Create Mail
In this step, we will create a mail class called MyTestMail to handle email sending. Inside this class, we will define which view to use and pass in the user object. To create this class, run the following command:
php artisan make:mail MyTestMail
app/Mail/MyTestMail.php
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class MyTestMail extends Mailable
{
use Queueable, SerializesModels;
public $details;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($details)
{
$this->details = $details;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->subject('Test Mail')
->view('emails.myTestMail');
}
}
Step 3: Create Blade File
In this step, we will create a blade view file where we will write the email that we want to send. For now, we will just write some dummy text. Create the following files in the "emails" folder.
resources/views/emails/myTestMail.blade.php
My Website
{{ $details['title'] }}{{ $details['body'] }}Thank you
Step 4: Add Route
Finally, we will create the "MyTestMail" class to send our test email. Let's create a web route to test the email sending.
routes/web.php
Route::get('send_mail', function () {
$details = [
'title' => 'This is the title',
'body' => 'This is for testing email using Gmail SMTP'
];
\Mail::to('test@gmail.com')->send(new \App\Mail\MyTestMail($details));
dd("Sent!");
});
Now you can run and check the example.
Run Project:
php artisan serve
Open Link:
http://localhost:8000/send_mail
It will send you an email.