Laravel 9 Generate PDF and Attach To GMail Email Tutorial

Reading Time: 7 minutes
1,342 Views

Sending an email in web application is very common. Laravel provides the predefined Mail class used to send mail. We only need to use & configure it. The content of this article is very useful to understand the things that we need to send a email using SMTP.

Inside this article we will see Laravel 9 Generate PDF and attach to Gmail email by Gmail SMTP Server. We will use Gmail server and it’s SMTP details.

We will understand about the complete concept sending emails with attachment in laravel 9. Attach any attachment file with any file extension we use attachData() along with to() and subject() methods of Mail class in laravel.

To get the complete concept of this article you need SMTP details.

Learn More –

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.

Create Database & Connect

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE laravel_app;

To connect database with application, Open .env file from application root. Search for DB_ and update your details.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=root
DB_PASSWORD=root

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.

When we install we should see the given image in terminal

create-pdf-in-laravel-9-using-dompdf-package

SMTP Configuration

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=465
MAIL_USERNAME="xxxyyyzzz@gmail.com"
MAIL_PASSWORD="your_password"
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="xxxyyyzzz@gmail.com"
MAIL_FROM_NAME="Online Web Tutor"

//...

Make sure you have enabled google security setting form your gmail. go to Google account and click on “Account”. Once you are on the “Account” page, click on “Security“. Scroll down to the bottom and you will find “Less secure app access” settings. Set as ON.

Have a look into these images.

Create Controller

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 9 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 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.

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 9 Generate PDF and Attach To GMail Email Tutorial in a very detailed way.

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.