Back
Written by Sandeep B on Friday, June 7 2019

How to generate PDF and send it on mail in Laravel 5.8

Laravel Journey
Share:

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

Table of contents

  • Description
  • About SMTP sever
  • External Packages
  • View
  • Controller
  • Route

Description

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

About SMTP sever

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.

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"

External Packages

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


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

Add the following in your controller

use PDF;

View

Create a blade file on resources directory. Inside I created a directory called mails and here the name is mail.

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

Controller

At the end your controller looked like this

 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'));
 }

Explanation

  • Controller takes 3 post parameters such as
    • $data["email"]=$request->get("email");
    • $data["client_name"]=$request->get("client_name");
    • $data["subject"]=$request->get("subject");
  • $pdf = PDF::loadView('mails.mail', $data) Loaded the blade template from mails directory for the contents of the pdf. The $data is also passing to the blade file. So i can use $data on that file according to our needs
  • 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"); }); -- 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.
  • the output file name is 'invoice.pdf' and it wil be attached with the mail
  • Route

    ```php Route::post('/sendmail','BasicController@sendmail'); ``` Rest Client ![Rest Client](http://basic.poornathaevents.com/laravel_api/public/images/insomnia_screen.PNG)

    Yup . Thats it.

    Thumbs up

Edit this post on GitHub
Sandeep B

Sandeep B

Frontend engineer writing about Angular, JavaScript, and the occasional deep dive into whatever's currently breaking my build.

Subscribe to my
Newsletter

Subscribe to my newsletter to receive exclusive content, latest news and updates