In this tutorial, we will discuss the Laravel 8 send email example. This post will give you a simple example of sending an email in laravel 8 using Gmail SMTP.
Use the following steps to get ready mail functionality in laravel 8:
Step 1: .env Configuration
.env
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=username@gmail.com
MAIL_PASSWORD=gmail_password
MAIL_ENCRYPTION=ssl
MAIL_FROM_ADDRESS=mymail@gmail.com
MAIL_FROM_NAME="${APP_NAME}"
Step 2: Create MyTestMail class
So let's run the following command to create MyTestMail inside app directory.
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 subject')
->view('emails.mymail_template');
}
}
Step 3: Create Blade View
Create blade view file and write email template that we want to send.
resources/views/emails/mymail_template.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Mails</title>
</head>
<body>
<h1>{{ $details['title'] }}</h1>
<p>{{ $details['body'] }}</p>
<p>Thank you</p>
</body>
</html>
Step 4: Add Route
Create the web route for testing sendemail.
routes/web.php
Route::get('send-mail', function () {
$details = [
'title' => 'Test title',
'body' => 'Test message'
];
\Mail::to('your_receiver_email@gmail.com')->send(new \App\Mail\MyTestMail($details));
dd("Email is Sent.");
});
Step 5: Run Project:
Now you can run and check example.
php artisan serve