In this article we will learn how to send mail in Laravel 8
Follow the below steps to send mail in laravel.
In step first, we have to set mail configuration settings with mail driver in .env file like below example.
.env
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
[email protected] #sender email id
[email protected] #sender email password
MAIL_ENCRYPTION=ssl
[email protected]
MAIL_FROM_NAME="Teknowize" #your app name
In second step we will create TestMail class for mail sending.
Go to your terminal and simply run this below command.
php artisan make:mail TestMail
Output
Create a new MailController.php controller
php artisan make:controller MailController
app \Http \Controllers\ MailController.php
<?php
namespace App\Http\Controllers;
use App\Mail\TestMail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
class MailController extends Controller
{
function send_mail(){
$email_id = '[email protected]';
$msg = [
'title' => 'Hello! from Teknowize',
'body' => 'This is my test mail in Laravel 8'
];
Mail::to($email_id)->send(new TestMail($msg));
return' Mail send successfuly to '.$email_id ;
}
}
routes\web.php
<?php
use App\Http\Controllers\MailController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/
Route::get('send_mail', [MailController::class, 'send_mail']);
In this step, open your resources/views folder then create a Email folder then create mail.blade.php in Email folder.
You can also create blade page in resources/views without making any folder.
resources \views \Email \mail.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>{{ $msg['title'] }}</h1>
<p>{{ $msg['body'] }}</p>
<a href="https://www.teknowize.com/"><button style="background:blue;color:whitesmoke">Learn More</button></a>
<p>Thank you!</p>
</body>
</html>
app\Mail\TestMail.php
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class TestMail extends Mailable
{
use Queueable, SerializesModels;
public $msg;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($msg)
{
$this->msg = $msg;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->subject('Test Mail From Teknowize')->view('Email/mail');
}
}
Result -