How to Send Emails in Laravel Using Controller
Sending emails is an important part of any web application, and Laravel provides a simple and elegant way to send emails using its built-in Mail facade. In this tutorial, we'll show you how to send emails in Laravel using controllers, models, and routes. We'll start by creating a new controller, then we'll write the code to send the email, and finally, we'll create a route to trigger the email sending process. So, let's get started!
1. First, create a new controller using the following command:
php artisan make:controller EmailController
2. Next, open the EmailController.php file located in the "app/Http/Controllers" directory and add the following code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
class EmailController extends Controller
{
public function sendEmail()
{
Mail::raw('This is the content of mail body', function($message) {
$message->from('admin@abc.com', 'GOODTeam');
$message->to('rizikmw@gmail.com');
$message->subject('ABC');
});
return 'Send Email Successfully';
}
}
3.Next, create a route to the sendEmail method in the web.php file located in the "routes" directory:
Route::get('/rhn', [\App\Http\Controllers\EmailController::class, 'sendEmail']);
4. Finally, you can test the route by visiting the "/rhn" URL in your browser.
OUTPUT
^ "Send Email Successfully"