How to generate PDF and send it on mail in Laravel 11

Laravel 10 Send Email with PDF Attachment Tutorial will teach you how to send emails with PDF attachments in Laravel using the laravel PDF package.

PDF stands for Portable Document Format. It is a popular file format created by Adobe.

If you are a laravel developer willing to know how to build a controller that helps you send PDF attachments with mail in Laravel, then this guide is for you.

Laravel 11 Generate PDF and sent with Email Example

  • Step 1: Install Laravel App
  • Step 2: Install PDF Package
  • Step 3: Set Up Laravel PDF
  • Step 4: Register SMTP in Env
  • Step 5: Set Up Send Email Controller
  • Step 6: Create Send PDF Attachment View
  • Step 7: Create Routes
  • Step 8: Run Application Server

# Install Laravel App

First install a fresh laravel 11 appliation using the below command.

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

# Install PDF Package DomPdf

Here i used exteranal package library for generating pdf on the go. Its called laravel-dompdf. From the the project directory type

composer require barryvdh/laravel-dompdf

Wait for the command to be completed execution.

After succesful execution go to the config >> app.php and add the following configuration.


'providers' => [
    ....
    Barryvdh\DomPDF\ServiceProvider::class,
],
'aliases' => [
    ....
    'PDF' => Barryvdh\DomPDF\Facade::class,
],

# Register SMTP in Env

In order to send a mail with pdf, you have to add the credentials inside the .env config file. You can look for this file inside your laravel project.

MAIL_DRIVER=smtp
MAIL_HOST=mail.domain.com
MAIL_PORT=587
MAIL_USERNAME=test@test.domain.com
MAIL_PASSWORD=the one you chose to create
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS=yourmail@provider.com
MAIL_FROM_NAME="Your Name"

You have to allow non-secure apps if you are willing to use Gmail, it will enable the less secure app; make sure to visit here.

# Create Send Email Controller

After invoking the above command, a new file is created; hence, you have to open the app/Http/Controllers/MailController.php file further and add the given code to the file.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Mail;

class MailController extends Controller
{
   public function sendmail(Request $request){
        $data["email"]=$request->get("email");
        $data["client_name"]=$request->get("client_name");
        $data["subject"]=$request->get("subject");

        $pdf = PDF::loadView('mails.mail', $data);

        try{
            Mail::send('mails.mail', $data, function($message)use($data,$pdf) {
            $message->to($data["email"], $data["client_name"])
            ->subject($data["subject"])
            ->attachData($pdf->output(), "invoice.pdf");
            });
        }catch(JWTException $exception){
            $this->serverstatuscode = "0";
            $this->serverstatusdes = $exception->getMessage();
        }
        if (Mail::failures()) {
             $this->statusdesc  =   "Error sending mail";
             $this->statuscode  =   "0";

        }else{

           $this->statusdesc  =   "Message sent Succesfully";
           $this->statuscode  =   "1";
        }
        return response()->json(compact('this'));
  }
}

We are now going to create a mail template using the Laravel blade file.

Make sure to create resources\views\mails\mail.blade.php file and insert the following code into the file.

Hi, Admin <br/>
This is just a test mail.<br />
Thank you!!

# Create Send PDF Attachment View

Further, you have to set up the view file. You need to get into the resources/views folder; here, you must make the home.blade.php and add the given code to the file.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel 11 Email PDF Attachment Example</title>

    </head>
    <body class="antialiased">
       <h2>A test mail sent from positronx.io</h2>
       <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam non ligula ligula. </p>
    </body>
</html>

# Create Routes

Go ahead and look for the resources/ folder; inside here, you will see web.php file. Make sure to define the route that will help you shoot the mail with a pdf attachment.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\MailController;

Route::get('send-pdf-mail', [MailController::class, 'sendmail']);

# Run Application Server

We have successfully created the functionality; now you need to run the server using given command. Make sure to test the feature using provided url.

php artisan serve

http://127.0.0.1:8000/send-pdf-mail