How to generate PDF and send it on mail in Laravel 5.8
Tags: mail, pdfgeneration, laravel5
Published: 2019-06-07 07:24:29

---
title: How to generate PDF and send it on mail in Laravel 5.8
published: true
description: A simple code snippet to generate pdf and send mail attached with it. 
tags: mail, pdfgeneration,laravel5
series: Laravel Journey
cover_image: https://i.ytimg.com/vi/sdPhUIcDMMQ/maxresdefault.jpg
---

Have you ever wondered how to generate pdf and sent as an attachment with the mail for clients?

Who am I kidding? Google was here even before you heard the word 'mail'. If you are developer you had already googled it and done it right away.

Anyway if you have never thought about it or you gotta try it out on laravel ,
here it goes.

Before that if you are having a bad day,Let me cherish you first. skip ahead if you dont wanna cheer up.

Everything happend in your life for a reason . ( Most motivational content should start with this ). Think like i am gonna overcome this instead of thinking why this happend to me.  Eat atleast what can you get. Try to improve your social circle,Learn everyday. Everything will be fine sooner or later. 

#Main content from Here

<h2>Table of contents</h2>
<ul>
<li>Description</li>
<li>About SMTP sever</li>
<li>External Packages</li>
<li>View</li>
<li>Controller</li>
<li>Route</li>
</ul>

<center><h1><u>Description</u></h1></center>
 [Laravel] (https://laravel.com/) is an open-source PHP framework, which is robust and easy to understand. It follows a model-view-controller design pattern. Laravel reuses the existing components of different frameworks which helps in creating a web application.

<center><h1><u>About SMTP sever</u></h1></center>

For sending mail ofcourse you need a smtp server . You need to configure on your server to initialise the mail service. 

After setting up mail server in control panel( I will cover that in another post)
we need to included the credentials to the .env file of the laravel project. 

```env
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"
```
<center><h1><u>External Packages</u></h1></center>
Here i used exteranal package library for generating pdf on the go. Its called 
[laravel-dompdf](https://github.com/barryvdh/laravel-dompdf).
From the the project directory type

```cmd
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.

```php

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



Add the following in your controller

```php
use PDF;
```
<center><h1><u>View</u></h1></center>

Create a [blade](https://laravel.com/docs/5.8/blade) file on resources directory. Inside I created a directory called mails and here the name is mail. 

```html
<h1>Mail body goes  here</h1>
<p>pass here anything you want inside $data array in your controller.</p> 

```
<center><h1><u>Controller</u></h1></center>
At the end your controller looked like this

```php

 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'));
 }
```
<h1><u>Explanation</u></h1>
<ul>
<li>Controller takes 3 post parameters such as
<ul>
<li> <code>$data["email"]=$request->get("email");</code></li>
<li> <code>$data["client_name"]=$request->get("client_name");</code></li>
<li> <code>$data["subject"]=$request->get("subject");</code></li>
</ul>
<li><code>$pdf = PDF::loadView('mails.mail', $data)</code> 
Loaded the blade template from mails directory for the contents of the pdf. The <code>$data</code> is also passing to the blade file. So i can use <code>$data</code> on that file according to our needs</li>

<li><code> 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");
            }); </code>   --  Using the same blade file for the sake of the post. You can use any blade file for the body of the email . Remaining are kind of self explanotory. Just using all the variables from the post request.</li>

<li> the output file name is 'invoice.pdf' and it wil be attached with the mail</li>
        
<center><h1>Route</h1></center>
```php
Route::post('/sendmail','BasicController@sendmail');
```
<center>Rest Client</center>
![Rest Client](http://basic.poornathaevents.com/laravel_api/public/images/insomnia_screen.PNG)

Yup . Thats it.

![Thumbs up](https://media.giphy.com/media/JPsFUPp3vLS5q/giphy.gif)