Learn Laravel 10 Generate PDF and Send Email Example Step-by-Step

In this tutorial, you will learn how to generate PDF and send email in Laravel 10 using dompdf and Laravel Mail facade. Follow the step-by-step guide to create an example of sending an email with a PDF attachment.

 Learn Laravel 10 Generate PDF and Send Email Example Step-by-Step

This tutorial will teach you how to generate PDFs and send emails in Laravel 10. With the help of Dompdf, you'll also learn how to send email attachments in Laravel 10. Follow a few simple steps to create a basic example of sending an email with a created PDF file in your Laravel application. Don't miss out on this opportunity to learn how to easily generate and send professional-looking PDFs to your clients and customers.

Step 1: Install Laravel

We'll start from the beginning and walk through the steps needed to create a new Laravel application. To get started, open your terminal or command prompt and run the following command:

composer create-project --prefer-dist laravel/laravel blog

Step 2: Install dompdf Package

To begin, let's install the "barryvdh/laravel-dompdf" package in our Laravel application using Composer. Simply execute the Composer command below to install the package.

composer require barryvdh/laravel-dompdf

Step 3: Make Configuration

For the first step, we need to configure the mail settings for our Laravel application. This includes specifying the mail driver, host, port, username, and password to be used by Laravel when sending emails. You can achieve this by adding the following configuration to your application:

.env

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=mygoogle@gmail.com
MAIL_PASSWORD=password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=mygoogle@gmail.com
MAIL_FROM_NAME="${APP_NAME}"

Step 4: Create Mail Class

As we are starting from scratch, our first step is to create an email for testing purposes using the Laravel Mail facade. To do this, we can run the following command:

php artisan make:mail MailExample

Now that you have created a new folder "Mail" in the app directory with a MailExample.php file, you can proceed to copy and paste the code below 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'),
        ];
    }
}

Step 5: Add Route

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

routes/web.php

Route::get('send-email-pdf', [PDFController::class, 'index']);

Step 6: Add Controller

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

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 Title";
        $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');
    }
       
}

Step 6: Create View File

In the final step, we will create the layout for the email template by creating a new file named "myTestMail.blade.php" inside the "resources/views/emails" directory. Add the following code to this file:

resources/views/emails/myTestMail.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>PDF</title>
</head>
<body>
    <h1>{{ $title }}</h1>
    <p>{{ $body }}</p>
     
    <p>Thank you</p>
</body>
</html>

You have completed all the necessary steps, and now it's time to run your Laravel application. Open your terminal or command prompt and enter the following command to start the app:

php artisan serve

After completing all the necessary steps, open your web browser and type the URL provided below to view the output of the Laravel application:

http://localhost:8000/send-email-pdf