How to Send PDF Attachment using Email in Laravel 10

Last Updated on by in Laravel

In this comprehensive tutorial, you will learn how to send PDF attachments via email using Laravel.

Sending emails with attachments is a common requirement in modern web applications for functions such as sending invoices, reports, or downloadable content to users.

Laravel makes it easy to handle this process with its robust mail functionality and integration with third-party email services.

To build this feature, we’ll be using niklasravnsborg/laravel-pdf package.

The niklasravnsborg/laravel-pdf package is a useful tool for Laravel developers to generate PDF files directly from HTML views. It integrates seamlessly with Laravel, allowing you to design PDFs using Blade templates and style them with CSS. This package simplifies PDF generation and provides advanced features such as custom headers and footers, watermarks, and security settings.

For Laravel developers, the ability to send PDF attachments via email can enhance your application’s functionality and user experience. This feature allows you to automate communication with your users, keep them informed, and provide them with necessary documents in a convenient way.

In this tutorial, we will cover:

  • Setting up email configuration: Prepare your Laravel application with the required email service settings.
  • Generating a PDF file: Create a PDF file within Laravel using libraries like Dompdf or TCPDF.
  • Creating a mailable: Define the email layout and content using Laravel’s mailable classes.
  • Attaching the PDF file: Add the generated PDF file as an attachment to your email.
  • Sending the email: Use Laravel’s mail function to send the email with the attached PDF.

By the end of this tutorial, you will have the skills to generate and send PDF attachments via email in your Laravel projects, improving communication and enhancing the user experience. Let’s get started!

Laravel 10 Send PDF Attachment with Email Example

  • Step 1: Build Laravel Project
  • 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: Build New Routes
  • Step 8: Run Application Server

Build Laravel Project

A new laravel application can be created using Composer. If you have installed the Composer, then you can run the given command to build a new project.

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

Install PDF Package

To mail PDF attachments in Laravel is made possible by the laravel-pdf package. This library does the core work for us; you have to install it to take advantage.

composer require niklasravnsborg/laravel-pdf

Set Up Laravel PDF

We have to move into the app.php file that you can see in the config/ directory.

You must register the service provider and facades in providers and aliases, respectively.

'providers' => [
  /* Application Service Providers */
   niklasravnsborg\LaravelPdf\PdfServiceProvider::class
],
'aliases' => Facade::defaultAliases()->merge([
   'PDF' => niklasravnsborg\LaravelPdf\Facades\Pdf::class
])->toArray(),

We are now going to run the command; our purpose is to publish the library config file to the config folder.

php artisan vendor:publish

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=smtp.gmail.com 
MAIL_PORT=587 
MAIL_USERNAME= USER_NAME_GOES_HERE
MAIL_PASSWORD= PASSWORD_GOES_HERE
MAIL_ENCRYPTION=tls 

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.

Set Up Send Email Controller

You have to run the command to generate a new controller. All the code with logic goes here into this file to build the desired feature.

php artisan make:controller PdfMailController

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

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Mail;
class PdfMailController extends Controller
{
    public function index(Request $request){
        {
            $data["email"] = "demo@yahoo.com";
            $data["title"] = "PositronX";
            $data["body"] = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
     
            $files = [
                public_path('attachments/demo.jpeg'),
                public_path('attachments/tariff_rates.pdf'),
            ];
      
            Mail::send('mail.demo_mail', $data, function($message)use($data, $files) {
                $message->to($data["email"])
                        ->subject($data["title"]);
     
                foreach ($files as $file){
                    $message->attach($file);
                }            
            });
    
            echo "Mail successfully sent!";
        }       
 }
}

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

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

Hi, Admin <br/>
This is just a demo 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 9 Email PDF Attachment Example</title>
    </head>
    <body class="antialiased">
       <h2>A demo mail sent from positronx.io</h2>
       <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam non ligula ligula. </p>
    </body>
</html>

Build New 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\PdfMailController;
/*
|--------------------------------------------------------------------------
| 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-pdf-via-mail', [PdfMailController::class, 'index']);

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-via-mail

How to Send PDF Attachment using Email in Laravel

Conclusion

In this tutorial, you’ve learned how to effectively send PDF attachments via email using Laravel and the niklasravnsborg/laravel-pdf package.

By mastering this functionality, you can easily automate communication with your users and provide them with important documents such as invoices and reports.

Now that you have the skills to generate PDFs from HTML views and attach them to emails, you can enhance your Laravel applications and improve the overall user experience. Happy Coding!

Age calculator tool

🎂✨ Discover your age in detail and with countdown to your next birthday with fun facts! 🎈🎉

Calculate your age now!
Digamber - Author positronX.io

Hi, I'm Digamber Singh, a New Delhi-based full-stack developer, tech author, and open-source contributor with 10+ years' experience in HTML, CSS, JavaScript, PHP, and WordPress.