Laravel Send Email Using Markdown Template
Hello artisans, today I’ll show you how you can send email easily using Markdown. Laravel Markdown provides components, tables, email links, buttons, embed images etc. So, let’s see how we can use this beautiful feature in our app.
Note: Tested on Laravel 8.65.
Table of Contents
Create and Setup Controller
We will start by creating our controller. So, fire this below command in your terminal
php artisan make:controller EmailController
This will create a file under App\Http\Controllers. Open up the file and put the below code into EmailController
<?php
namespace App\Http\Controllers;
use App\Mail\SendEmail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
class EmailController extends Controller
{
public function sendEmail(Request $request)
{
$name = [
'name' => 'John',
];
try {
Mail::to('[email protected]')->send(new SendEmail($name));
return back()->with('msg','Email Send Successfully');
} catch (\Exception $e) {
echo 'Error - '.$e;
}
}
}
Create Route
Put the below route in your web.php file.
Route::get('sendemail', [\App\Http\Controllers\EmailController::class,'sendEmail'])->name('sendemail');
Create and Configure Mail Class
For creating Mail class fire the below command in your terminal
php artisan make:mail SendEmail --markdown=emails.sendmail
After hitting the command we can see that under App\Mail SendMail class has been generated. Now, open this class and paste the below code.
<?php
namespace App\Mail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class SendEmail extends Mailable
{
use Queueable, SerializesModels;
private $content;
public function __construct($content)
{
$this->content = $content;
}
public function build()
{
return $this->markdown('emails.sendmail')
->with('content',$this->content);
}
}
Setup View
Now open the sendmail.blade.php and paste the following code into your blade file
@component('mail::message')
# Dear, {{$content['name']}}
You are receiving this email because we received a signup request for your this mail account.
@component('mail::button', ['url' => url('/') ])
Click Here
@endcomponent
If you did not request a signup , no further action is required.
Thanks,
{{ config('app.name') }}
@endcomponent
And that’s it, you’re done. Finally, check your .env file for Mail Configuration (if everything ok or not).
That’s all for toady. Thanks for reading.