In this article, we will see how to send mail using gmail in laravel 9. we will learn laravel 9 to send mail using gmail SMTP server. Laravel and Symfony Mailer provide drivers for sending email via SMTP, Mailgun, Postmark, Amazon SES, and sendmail
, allowing you to quickly get started sending mail through a local or cloud based service of your choice.
So, let's see send mail in laravel 9 using gmail.
Step 1: Install Laravel 9
Step 2: Setup .env file Configuration
Step 3: Create Mailable Class
Step 4: Create Blade File
Step 5: Create Route
In this step, we will create laravel application using the below command.
composer create-project laravel/laravel example-app
Now, we will set up mail configuration in the .env file.
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=your_username
MAIL_PASSWORD=your_password
MAIL_ENCRYPTION=tls
[email protected]
MAIL_FROM_NAME="${APP_NAME}"
Note: When 2-step Verification is turned on for an account, access to less secure apps is automatically disabled, unless users are in a configuration group that allows access to less secure apps. Go to Manage access to less secure apps below.
In this step, we will create a mailable class using the laravel artisan command.
php artisan make:mail GmailTestMail
This command will create a new file app/Mail/GmailTestMail.php.
<? php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class GmailTestMail extends Mailable{
use Queueable, SerializesModels;
public $user;
public function __construct($user){
$this->user = $user;
}
public function build(){
return $this->subject('This is gmail testing')
->view('emails.test');
}
}
Let's create a file under app/resources/views/emails/test.blade.php
and add this code.
<!DOCTYPE html>
<html>
<head>
<title>How To Send Mail Using Gmail In Laravel 9 - Websolutionstuff</title>
</head>
<body>
<h5>{{ $user['name'] }}</h5>
<p>{{ $user['info'] }}</p>
<p>Thank you</p>
</body>
</html>
In this step, we will create a route for sending emails.
routes/web.php
Route::get('send-mail', function () {
$user = [
'name' => 'Websolutionstuff',
'info' => 'This is gmail example in laravel 9'
];
\Mail::to('[email protected]')->send(new \App\Mail\GmailTestMail($user));
dd("Successfully send mail..!!");
});
You might also like: