How To Generate PDF and Send Email in Laravel 11?

Jun 15, 2024 | Laravel 11 Laravel


Hello Dev,

In this example, you'll discover how to generate PDFs and send emails in Laravel 10. We'll cover using Dompdf to generate a PDF file and attach it to an email. This tutorial will guide you through the process of sending an email with a PDF attachment in Laravel 10.

We'll use Dompdf to create the PDF file and then send an email with the generated PDF attached. Follow these steps to create a basic example of sending an email with a PDF file in your Laravel application.

Step 1: Install Laravel 11

If you haven't already, create a new Laravel project:

composer create-project laravel/laravel example-app
Step 2: Install dompdf Package

To begin, we'll install the "barryvdh/laravel-dompdf" composer package in your Laravel application using the following composer command.

composer require barryvdh/laravel-dompdf
Step 3: Make Configuration

In the initial step, you need to configure email sending by specifying the mail driver, mail host, mail port, mail username, and mail password. This configuration allows Laravel to use these sender details for sending emails. Simply add the following configuration settings.

.env
MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=mygoogle@gmail.com
MAIL_PASSWORD=rrnnucvnqlbsl
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=mygoogle@gmail.com
MAIL_FROM_NAME="${APP_NAME}"
Step 4: Create Mail Class

Starting from scratch, in the first step, we'll create a test email using Laravel's Mail facade. Let's execute the following command.

php artisan make:mail MailExample

Now, you'll find a new folder named "Mail" within the app directory, containing a file named MailExample.php. Let's copy the following code and paste it into that file.

app/Mail/MailExample.php
<?php
  
namespace App\Mail;
  
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
use Illuminate\Mail\Mailables\Attachment;
  
class MailExample extends Mailable
{
    use Queueable, SerializesModels;
  
    public $mailData;
  
    /**
     * Create a new message instance.
     */
    public function __construct($mailData)
    {
        $this->mailData = $mailData;
    }
  
    /**
     * Get the message envelope.
     */
    public function envelope(): Envelope
    {
        return new Envelope(
            subject: $this->mailData['title'],
        );
    }
  
    /**
     * Get the message content definition.
     */
    public function content(): Content
    {
        return new Content(
            view: 'emails.myTestMail',
            with: $this->mailData
        );
    }
  
    /**
     * Get the attachments for the message.
     *
     * @return array

     */
    public function attachments(): array
    {
        return [
            Attachment::fromData(fn () => $this->mailData['pdf']->output(), 'Report.pdf')
                ->withMime('application/pdf'),
        ];
    }
}
Read Also: How To Load More Data on Page Scroll Using Ajax Jquery Laravel 11? Step 5: Add Route

In this step, we'll create routes for listing items. Open your "routes/web.php" file and add the following route.

routes/web.php
<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\PDFController;
  
/*
|--------------------------------------------------------------------------
| 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('send-email-pdf', [PDFController::class, 'index']);
Step 6: Add Controller

Here, we need to create a new controller named PDFController, which will handle the index method of the route. Let's add the following code:

app/Http/Controllers/PDFController.php
<?php
      
namespace App\Http\Controllers;
       
use Illuminate\Http\Request;
use App\Mail\MailExample;
use PDF;
use Mail;
    
class PDFController extends Controller
{
       
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data["email"] = "your@gmail.com";
        $data["title"] = "From ItErrorSolution.com";
        $data["body"] = "This is Demo";
    
        $pdf = PDF::loadView('emails.myTestMail', $data);
        $data["pdf"] = $pdf;
  
        Mail::to($data["email"])->send(new MailExample($data));
    
        dd('Mail sent successfully');
    }
       
}
Read Also: Laravel 11 Custom Validation Error Message Example Tutorial Step 7: Create View File

In the final step, let's create a file named myTestMail.blade.php (located at resources/views/emails/myTestMail.blade.php) to serve as the layout for the PDF file. Copy and paste the following code into the file:

resources/views/emails/myTestMail.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>ItErrorsolution.com</title>
</head>
<body>
    <h1>{{ $title }}</h1>
    <p>{{ $body }}</p>
     
    <p>Thank you</p>
</body>
</html>
Step: Run the Application

Now, to run the Laravel application, please type the following command and press enter:

php artisan serve

Now, open your web browser and enter the provided URL to view the output of the application.

View Your Application
http://localhost:8000/send-email-pdf

Feel free to ask if you have any questions or need further clarification!



Tags :
#Laravel 11
#Laravel
ItErrorSolution.com

ItErrorSolution.com

"Hey there! I'm a full-stack developer and proud owner of ItErrorSolution.com, based right here in India. I love nothing more than sharing handy tips and tricks with my fellow developers through easy-to-follow tutorials. When it comes to coding, I'm all about PHP, Laravel, Angular, Vue, Node, JavaScript, jQuery, CodeIgniter, and Bootstrap – been hooked on them forever! I'm all about putting in the work and staying committed. Ready to join me on this journey to coding?"