Email Sending Helper Class in Laravel
In a Laravel application, you may need to send custom emails for various purposes. To simplify the process, you can create a GeniusMailer class that encapsulates the functionality of sending emails using Laravel's built-in Mail facade. This article will guide you through the steps to add the GeniusMailer class, import it into a controller, and demonstrate how to send a custom email.
Step 1: Adding the GeniusMailer Class
To add the GeniusMailer class, follow these steps:
1. Create a new PHP file named `GeniusMailer.php` in the `App\Classes` directory.
2. Copy and paste the following code into the `GeniusMailer.php` file:
<?php
namespace App\Classes;
use Illuminate\Support\Facades\Mail;
class GeniusMailer
{
public function sendCustomMail($view, $to, $subject, $viewData)
{
$objDemo = new \stdClass();
$objDemo->to = $to;
$objDemo->subject = $subject;
try {
Mail::send('email.' . $view, ['viewData' => $viewData], function ($message) use ($objDemo) {
$message->to($objDemo->to);
$message->subject($objDemo->subject);
});
} catch (\Exception $e) {
die($e->getMessage());
// return $e->getMessage();
}
return true;
}
}
Step 2: Importing the GeniusMailer Class into a Controller
To use the GeniusMailer class in a controller, follow these steps:
1. Create a new controller file or open an existing one.
2. Add the following line at the top of the controller file to import the GeniusMailer class:
use App\Classes\GeniusMailer;
Step 3: Sending a Custom Email
Inside a method in the controller, you can use the GeniusMailer class to send a custom email. Here's an example:
$mail_subject = 'Enquire Now';
$data = [
'name' => 'hello',
'email' => 'hello@gmail.com',
];
$mailer = new GeniusMailer();
$mailer->sendCustomMail('enquire_now', 'to@gmail.com', $mail_subject, $data);
Make sure to replace `'enquire_now'` with the name of the email view file you want to use.
Step 4: Creating the Email View File
Create the `enquire_now.blade.php` email view file in the `resources/views/email/` directory. Customize the content of the email view file using HTML and Blade syntax according to your needs.
Leave A Comment