Laravel 8 Tutorial - Send Email using Gmail
In this tutorial, we are going to learn how to send an email using Gmail in Laravel 8.
So, let's see how we can send an email using Gmail in Laravel 8. First of all, let's create a new controller.
To create a new controller, switch to the command prompt and run the following command:
php artisan make:controller MailController
Now, create a mail class. For that, run the following command:
php artisan make:mail TestMail
Now, switch to the project and make the configuration for email. Go to the .env
file and add your Gmail account details as follows:
MAIL_MAILER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=465
MAIL_USERNAME=testemail@gmail.com
MAIL_PASSWORD=12345678
MAIL_ENCRYPTION=ssl
MAIL_FROM_ADDRESS=testemail@gmail.com
MAIL_FROM_NAME="${APP_NAME}"
Next, go to your Gmail account and click on the Account icon. Then, click on Security. Scroll down the page and make "Less secure app access" on.
Now, switch to the command prompt and re-run the application. Then, type the following command:
php artisan serve
Now, switch to the project and go to the app
directory, then mail
. From here, open TestMail.php
and write the following code:
public $details;
public function __construct($details)
{
$this->details = $details;
}
public function build()
{
return $this->subject('Test Mail From Surfside Media')->view('emails.TestMail');
}
Next, let's create a view. Go to the views
directory and create a new folder named emails
. Inside this folder, create a new file named TestMail.blade.php
and write the following code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test Mail</title>
</head>
<body>
<h1>{{ $details['title'] }}</h1>
<p>{{ $details['body'] }}</p>
<p>Thank you</p>
</body>
</html>
Now, switch to the project and open MailController
. Inside the MailController
, create a function:
public function sendEmail()
{
$details = [
'title' => 'Mail from Surfside Media',
'body' => 'This is for testing email using gmail'.
];
\Mail::to('your_receiver_email@gmail.com')->send(new TestMail($details));
return "Email is Sent.";
}
Also, import Mail, so before the class, write the following:
use App\Mail\TestMail;
Now, let's create a route for this function. Go to web.php
and create a new route:
Route::get('/send-mail',[MailController::class,'sendEmail']);
Alright, now let's check. Switch to the browser and go to /send-mail
. Email sent!
Now, let's check the email in Gmail. Go to your Gmail account and refresh the page. You can see the mail. Let's open it. Here, you can see the title and message.
So, in this way, you can send an email using Gmail in Laravel 8.