Send Mail with PDF Attachment in Laravel 8

Reading Time: 6 minutes
8,502 Views

Sending Emails is a commonly used functionality in every application. Sometimes we send with some attachment or some times without any attachment. Inside this article we will see the concept of send mail with pdf attachment in laravel 8.

This tutorial will be step by step guide to explain you about each step in defined details.

We will generate the PDF file and then send to email in Laravel.

Let’s get started.


Laravel Installation

We will create laravel project using composer. So, please make sure your system should have composer installed. If not, may be this article will help you to Install composer in system.

Here is the command to create a laravel project-

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

To start the development server of Laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.


Install dompdf 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

When we install we should see the given image in terminal


Package Configuration in Application

Successfully, we have installed above. Next, we need to set some application configuration.

Open app.php from /config/app.php

Search for the array of Providers and aliases. Add the given code into providers and aliases array.

//.. Other Codes

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

Mail SMTP Configuration with Laravel 8

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=YourEmail@gmail.com
MAIL_PASSWORD=YourPassword
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=YourEmail@gmail.com
MAIL_FROM_NAME="${APP_NAME}"

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.


Add Route

To add application route, open up the file web.php from /routes.

Open web.php and add this following code.

# Import Controller Class
use App\Http\Controllers\PDFController;

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

Create Controller

Open laravel application into terminal and run this following command. This command will create a controller class file at location /app/Http/Controllers

$ php artisan make:controller PDFController

Open controller file and write the given code into that.

<?php

namespace App\Http\Controllers;

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

class PDFController extends Controller
{
    public function index()
    {
        $data["email"] = "SendToEmail@gmail.com";
        $data["title"] = "Sample Mail with PDF From OnlineWebTutorBlog.com";
        $data["body"] = "Hi user, This is sample message sent for testing with PDF";
  
        $pdf = PDF::loadView('emails.myTestMail', $data);
  
        Mail::send('emails.myTestMail', $data, function($message)use($data, $pdf) {
            $message->to($data["email"], $data["email"])
                    ->subject($data["title"])
                    ->attachData($pdf->output(), "text.pdf");
        });
  
        dd('Mail sent successfully');
    }
}

Create Email Template File

Next, we need to create an email folder inside /resources/views directory. Inside email folder, then create a file named as myTestMail.blade.php.

This template file will be the email view which we sent into mail.

Open file myTestEmail.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Mail Title From onlinewebtutorblog.com</title>
</head>
<body>
    <h1>{{ $title }}</h1>
    <p>{{ $body }}</p>
     
    <p>Thanks, Online Web Tutor Support Team</p>
</body>
</html>
  

Application Testing

Run this command into project terminal to start development server,

php artisan serve

Open up the URL – http://localhost:8000/send-email-with-pdf

We hope this article helped you to learn about i.e Send Mail with PDF Attachment in Laravel 8 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.

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