10-Apr-2023
.
Admin
Hi Dev,
In this article I’m going to share how to generate PDF and attach it to the email.
I will give you step by step implementation of how to use laravel 8 generate PDF and attach to email example.So let's follow bellow step.
Step 1 : Install Laravel Application
first, we will install laravel fresh version. so let's run bellow command:
composer create-project --prefer-dist laravel/laravel blog
Step 2 :Install Package & Config
At first we need to install barryvdh/laravel-dompdf package. Run this composer command to install the package:
composer require barryvdh/laravel-dompdf
Now open .env file and set your SMTP credentials:
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=null
MAIL_FROM_NAME="${APP_NAME}"
Step 3 : Create Controller
Create a test controller and make a function to send email:
app/HTTP/Controllers/TestController
<?php
namespace App\Http\Controllers;
use PDF;
use Mail;
class TestController extends Controller
{
public function sendMailWithPDF()
{
$data["email"] = "test@gmail.com";
$data["title"] = "Welcome to NiceSnippets.com";
$data["body"] = "This is the email body.";
$pdf = PDF::loadView('mail', $data);
Mail::send('mail', $data, function ($message) use ($data, $pdf) {
$message->to($data["email"], $data["email"])
->subject($data["title"])
->attachData($pdf->output(), "test.pdf");
});
dd('Email has been sent successfully');
}
}
Step 4 : Create PDF View
Now we’ll create the PDF view which will be attached to the email. Go to resources>views folder and create mail.blade.php file. Then paste this simple PDF view:
resources/views/mail.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 8 Generate PDF And Attach To Email Example - NiceSnippets.com</title>
</head>
<body>
<h3>{{ $title }}</h3>
<p>{{ $body }}</p>
<p>
Regards,<br/>
NiceSnippets.com
</p>
</body>
</html>
Step 5 : Define Routes
routes/web.php
<?php
use App\Http\Controllers\TestController;
use Illuminate\Support\Facades\Route;
Route::get('send-email', [TestController::class, 'sendMailWithPDF']);
Now run the project:
php artisan serve
Visit the send email route:
http://localhost:8000/send-email
#Laravel 8
#Laravel 7
#Laravel
#Laravel 6