DEV Community

Cover image for How to generate PDF and send it on mail in Laravel 5.8
Sandeep Balachandran
Sandeep Balachandran

Posted on • Updated on

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

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 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"
Enter fullscreen mode Exit fullscreen mode

External Packages


Here i used exteranal package library for generating pdf on the go. Its called
laravel-dompdf.
From the the project directory type
composer require barryvdh/laravel-dompdf
Enter fullscreen mode Exit fullscreen mode

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,
],
Enter fullscreen mode Exit fullscreen mode

Add the following in your controller

use PDF;
Enter fullscreen mode Exit fullscreen mode

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> 

Enter fullscreen mode Exit fullscreen mode

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'));
 }
Enter fullscreen mode Exit fullscreen mode

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

Route::post('/sendmail','BasicController@sendmail');
Rest Client



Rest Client

Yup . Thats it.

Thumbs up

Top comments (3)

Collapse
 
roelofjanelsinga profile image
Roelof Jan Elsinga

I've found that in order for this to work, I can't queue the email. I have to send the email instantly because the raw output of the PDF cannot be encoded into a valid JSON format. Can you confirm this?

Collapse
 
jonaymedina7 profile image
Jonay Medina

Hi, thanks for the tutorial. You could help me, I want my data like: mail, name, be loaded dynamically. example:

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=\Auth::user()->email;
MAIL_FROM_NAME=\Auth::user()->name;

could you help me in this

Collapse
 
sandeepbalachandran profile image
Sandeep Balachandran

Hey there, If you are seeing this, you can dynamically assign the sender address and name from controller itself if it is a feasible solution for your requirement.