Send Email Using Laravel
In this post we will learn how to send email using Swiftmailer library.
Steps:
Step 1: Install Laravel and Create Application
Step 2: Set configuration in .env
Step 2: Create Controller
Step 3: Create blade file
Step 4: Create Route
Step 5: Run application
Create laravel application : using below composer command create new laravel application
composer create-project --prefer-dist laravel/laravel sendemail
![](https://blogshub.co.in/wp-content/uploads/2023/01/image-4.png)
Get in application
cd sendemail
Set configuration using .env
Using gmail we will send an email in laravel so we have to configure our gmail credentials inside .env file
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=myemail@gmail.com
MAIL_PASSWORD=mypassword
MAIL_ENCRYPTION=tls
Now run below command for clear the cache
php artisan config:cache
Create Controller using artisan command as mention below
php artisan make:controller SendmailController
![](https://blogshub.co.in/wp-content/uploads/2023/01/image-5.png)
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Mail;
class SendmailController extends Controller
{
public function index(){
$data = array('content'=>"Test Mail using laravel - Blogshub.co.in!!");
Mail::send(['text'=>'mailer'], $data, function($message) {
$message->to('blogshub4@gmail.com', 'Blogshub')->subject('Test Mail using laravel - Blogshub.co.in');
$message->from('blogshub@gmail.com','Blogshub');
});
echo "Mmail sent successfully.";
}
}
Create view file resources\views\mailer.blade.php for mailer template.
<h1>Mail by blogshub.co.in</h1>
Create route in web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controller\SendmailController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('sendmailer',[SendmailController::class],'index');
Run application and access route
php artisan serve
![](https://blogshub.co.in/wp-content/uploads/2023/01/image-6.png)
http://127.0.0.1:8000/sendmailer