Laravel 10 Generate PDF and Attach To Email Tutorial

Reading Time: 10 minutes
480 Views

Improve the communication capabilities of your Laravel 10 application with our complete lesson on creating PDFs and easily attaching them to Gmail emails. Being able to create and send beautiful PDFs directly from your application can revolutionise your user experience in a world where digital documents drive efficiency.

This guide will walk you through the process of creating PDFs and effortlessly connecting them to Gmail emails within your Laravel 10 application. We’ve got you covered on all fronts, from setting up PDF creation libraries to configuring Gmail SMTP for attachments.

This tutorial covers the basic concepts of setting up an email system in Laravel, configuring the email settings, and attaching a PDF file.

Read More: Step-by-Step JSON Data Seeding with Laravel 10 Tutorial

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

How Do I Configure A Google App Password?

Google App Password is a 16-digit alphanumeric number that allows you to sign in to your Google Account from apps that do not support two-factor authentication.

If you enable app password, you will never have to reveal your primary account password again. App Passwords are only available to accounts with 2-Step Verification enabled.

Here’s how to create an app password so you can send and receive emails on your server.

Step #1 Login to Google Account

Go to myaccount.google.com (if not signed in, you will be asked to sign-in to your account)

Step #2 Enable 2-Step Verification

Before you can set up the app password, you must first enable 2-Step Verification on your account.

Read More: Laravel 10 Generate Dynamic Sitemap Example

To proceed to the Security page, click on the Security tab on the left-hand side and then on 2-Step Verification under the section Signing in to Google.

Click on Get Started and on the next page enter your password to verify your account and hit Next

You must now configure your phone.

Enter the phone number you want to use for verification, then choose how you want to get your code. It might be a text or a phone call. I’ll keep it as a text message and press Next.

Read More: Laravel 10 LogViewer: A Beautiful Log Viewer

Google will give you a verification code through text message. Enter the verification code and then click Next.

Google will confirm that 2-Step Verification is enabled on the next page.

To return to the Security page, click the back arrow next to the header.

Step #3 Setup Application password

Within the section Signing in to Google, you will notice a new option that says App passwords.

In case, if you are not able to see this App password there. Click on 2-Step Verification.

Verify your account by clicking on App passwords. You will be able to create app passwords for any app and device after verification.

Select Mail from the Select app and Other (custom name) from the Select device, and then give it a name. You can call it whatever you want; I’ll call it PHPMailer and click Generate.

Read More: Laravel 10 Telescope: Debugging and Monitoring Tool

You have now successfully created your app password. Copy and paste this code somewhere safe until you’ve added it to the PHP script.

Keep your email address and app password for SMTP configuration.

How To Configure SMTP in Laravel?

To configure SMTP details, open up the file .env from application root.

We will pass mail driver as gmail server, mail host, mail port, mail username, mail password.

//..

MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME="your_username@gmail.com"
MAIL_PASSWORD="your_app_password"
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="your_email_address@gmail.com"
MAIL_FROM_NAME="Online Web Tutor"

//...

How To Install PDF Package

Here, we will install a pdf package to laravel application. Open project in terminal and type this composer command to install.

$ composer require barryvdh/laravel-dompdf

It will installs PDF package into application which we will use to generate PDF.

Create Controller with Email Functions

Open project into terminal and run this command into it.

$ php artisan make:controller TestMailController

It will create TestMailController.php file inside /app/Http/Controllers folder.

Open controller file and write this code into it.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use PDF;
use Illuminate\Support\Facades\Mail;

class TestMailContoller extends Controller
{
    public function sendMailWithPDF()
    {
        $data["email"] = "sanjayxyz@gmail.com";
        $data["title"] = "Mail from Online Web Tutor";
        $data["body"] = "Test mail sent by Laravel  using SMTP.";

        $pdf = PDF::loadView("pdf_template", $data);

        Mail::send('mail', $data, function ($message) use ($data, $pdf) {
            $message->to($data["email"], $data["email"])
                ->subject($data["title"])
                ->attachData($pdf->output(), "onlinewebtutor.pdf");
        });

        dd("Email is Sent, please check your inbox.");
    }
}

Concept

Generate PDF and send to Email

$pdf = PDF::loadView("pdf_template", $data);

Mail::send('mail', $data, function ($message) use ($data, $pdf) {
    $message->to($data["email"], $data["email"])
        ->subject($data["title"])
        ->attachData($pdf->output(), "onlinewebtutor.pdf");
});

Create Email Templates

Create a fie pdf_template.blade.php and mail.blade.php inside /resources/views folder.

  • pdf_template.blade.php will be the template file which used to generate PDF file with that content.
  • mail.blade.php will be to send email means email template.

Read More: Laravel 10 and Google Pie Chart Integration Tutorial

Open pdf_template.blade.php and write this content into it. You can create your own content.

<!DOCTYPE html>
<html>

<head>
    <title>PDF Template</title>
</head>

<body>
    <p>PDF Template,</p> 
    <p>Greetings!!!</p>
    <p>We will use this template to generate PDF.</p>
    <p>{{ $title }}</p>
    <p>{{ $body }}</p>

    <p>Thank you</p>
</body>

</html>

Above content will be compiled and converted into a PDF file. This PDF file will be send to email.

Open mail.blade.php file and write this code into it.

<!DOCTYPE html>
<html>

<head>
    <title>Mail From Online Web Tutor</title>
</head>

<body>
    <p>Hi Users,</p> 
    <p>Greetings!!!</p>
    <p>Hope you are doing good.</p>
    <p>{{ $title }}</p>
    <p>{{ $body }}</p>

    <p>Thank you</p>
</body>

</html>

Add Route

Open web.php file from /routes folder. Add this route and code into it.

//...

use App\Http\Controllers\TestMailContoller;

//...

Route::get('send-mail', [TestMailContoller::class, 'sendMailWithPDF']);

Application Testing

Run this command into project terminal to start development server,

php artisan serve

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

We hope this article helped you to learn about Laravel 10 Generate PDF and Attach To GMail Email Tutorial in a very detailed way.

Read More: Laravel 10 and Google Line Chart Integration Tutorial

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more