Create Dynamic PDF in MPDF & Send as Attachment with Email in PHP using PHPMailer

Create Dynamic PDF in MPDF & Send as Attachment with Email in PHP using PHPMailer

Welcome folks I am back with another blog post. In this post we will be extending our previous post in which we have made a Dynamic PDF from HTML Form using MPDF Library. So I will suggest please read that before reading this one. In this post we will be extending the application by adding a feature which will allow users to actually send the generated PDF file as email by using PHPMailer in PHP. For mailing purpose we will be using a online service called mailtrap.io. This service allows us to test our application by sending test emails before you move on to production. Let’s get started by building this app from scratch.

First of all we will be installing the library PHPMailer from composer. Composer is a free program by which we can install dependencies by issuing some simple commands.

First of all install composer from here. Then after installing composer just type the below command to install the PHPMailer dependency in your project.

composer require phpmailer/phpmailer

 

After the installation is complete you will see this message as shown below

 

 

Now after installing the library just move on to the project which we have created earlier in the previous post. Just open the index.php file and copy paste the following code if you don’t have the code or if you are reading this for the first time.

<?php

// include the library

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require_once __DIR__ . '/vendor/autoload.php';

if(isset($_POST['fname']) && isset($_POST['lname']) && isset($_POST['email']) && isset($_POST['message']))
{
    $fname = $_POST['fname'];

    $lname = $_POST['lname'];

    $email = $_POST['email'];

    $message = $_POST['message'];

    // a new instance of the library

    $mpdf = new \Mpdf\Mpdf();

    $data = "";

    $data .= "<h1>Your Details</h1>";

    $data .= "<strong>First Name</strong> " . $fname . "<br>";

    $data .= "<strong>Last Name</strong> " . $lname . "<br>";

    $data .= "<strong>Email</strong> " . $email . "<br>";

    $data .= "<strong>Message</strong> " . $message . "<br>";

    $mpdf->WriteHtml($data);

    $mpdf->output("myfile.pdf","D");   
    

}

?>
<!DOCTYPE html>
<html>
<head>
<title>Generating PDF from HTML fORM using MPDF Library</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
</head>
<body>
<div class="container mt-5">

    <h1>Send PDF as Attachement</h1>

    <p>Fill out the Details to generate the pdf</p>

    <form action="index.php" method="post">
    
        <input type="text" placeholder="First Name" name="fname" class="form-control" required>
        <input type="text" placeholder="Last Name" name="lname" class="form-control" required>
        <input type="email" placeholder="Email" name="email" class="form-control" required>

        <textarea name="message" placeholder="Message" class="form-control" required>

        </textarea>

        <button class="btn btn-success" type="submit">Send</button>

    </form>

</div>
</body>
</html>

 

READ  How to Force a Image File to Download Automatically in PHP - Coding Shiksha

We have made this in the previous post. It will generate the PDF from the HTML Form as the user can enter details in it. So now we will make a separate function to send the generated email to any email address. For this we will remove the download function as we don’t want to generate the pdf we just want to store it in a variable. And then we can use that variable and send that to our custom function which will actually send it as a attachment with the email.

But before that first of all create a account on mailtrap.io. Create a free account and then it will give you free information such as smtp username and password that information you need to use in the PHP Script later on.

 

 

 

 

After creating the account on mailtrap. You need to go to the index.php file and include the PHPMailer Library into your php script. Just paste the 2 lines of code given below.

 

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

 

After including the library in the php script. Just delete this line from the php script which tells to invoke the download once the pdf file is ready.

 

$mpdf->output("myfile.pdf","D");

 

Now instead we will store the PDF File in a variable and send it through attachment. Now after deleting this line just write this line in place of this line as shown below

$pdf = $mpdf->output("","S");

Now after that we will store all the information such as firstname, lastname, email and message in a separate variable called as data so that we can also send this information as a label in the email. Just declare an array something like this as shown below.

$data = [
        "First Name" => $fname,
        "Last Name" => $lname,
        "Email" => $email,
        "Message" => $message
    ];

 

READ  How to Upload & Download Basic Video to MySQL Database in PHP - Coding Shiksha

Now after that we will create the custom function which will actually send the email with pdf attachment. Just create a new function something like this as shown below.

 

function sendEmail($pdf,$data){

}

 

Now it is expecting two variable namely the pdf data to be attached as email and also the details of the user which has been stored in an array called as data. Now copy paste all the code of the PHPMailer library this is the boilerplate code of the library so that we just need to make some tweaks to this code to make our app.

 

// Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->SMTPDebug = 2;                                       // Enable verbose debug output
    $mail->isSMTP();                                            // Set mailer to use SMTP
    $mail->Host       = 'smtp1.example.com;smtp2.example.com';  // Specify main and backup SMTP servers
    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    $mail->Username   = 'user@example.com';                     // SMTP username
    $mail->Password   = 'secret';                               // SMTP password
    $mail->SMTPSecure = 'tls';                                  // Enable TLS encryption, `ssl` also accepted
    $mail->Port       = 587;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('from@example.com', 'Mailer');
    $mail->addAddress('joe@example.net', 'Joe User');     // Add a recipient
    $mail->addAddress('ellen@example.com');               // Name is optional
    $mail->addReplyTo('info@example.com', 'Information');
    $mail->addCC('cc@example.com');
    $mail->addBCC('bcc@example.com');

    // Attachments
    $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
    $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name

    // Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}

 

Now in this code you need to replace our smtp values such as username, password ,host etc. I will show mine to you of mailtrap.io account. Yours may be different. Just include it as accordingly. In order to get the information in mailtrap steps are given below.

 

 

After including the following details you will get a similar sendEmail function as shown below. Just check your also.

 

function sendEmail($pdf,$data)
    {
       // Instantiation and passing `true` enables exceptions
$mail = new PHPMailer(true);

try {
    //Server settings
    $mail->SMTPDebug = 2;                                       // Enable verbose debug output
    $mail->isSMTP();                                            // Set mailer to use SMTP
    $mail->Host       = 'smtp.mailtrap.io';  // Specify main and backup SMTP servers
    $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    $mail->Username   = '2a1fe180baa913';                     // SMTP username
    $mail->Password   = 'eada7a225dacfd';                               // SMTP password
    $mail->SMTPSecure = 'tls';                                  // Enable TLS encryption, `ssl` also accepted
    $mail->Port       = 2525;                                    // TCP port to connect to

    //Recipients
    $mail->setFrom('test@email.com', 'Mailer');
    $mail->addAddress('joe@example.net', 'Joe User');


    // Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    $mail->send();
    echo 'Message has been sent';
} catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
}
    }
    

}

 

READ  jQuery FullCalendar Integration Using PHP MySQL & AJAX

Now we just have to call the function to send the email so just call the function like below.

 

sendEmail($pdf,$data);

 

As you press the Send Button in the Application you will see a bunch of text spitted out at last it will say message has been sent something like this as shown below.

 

 

Now if we check the mailtrap inbox you will find a email in it like this as shown below.

 

 

 

 

Now we have successfully sent the email in the mailtrap inbox but one thing is missing i.e. the pdf attachement now we have to pass the email as well as the PDF as an attachment for this we will add a single of code in the script or in the custom function . Just add this line of code in order to include the pdf attachment.

 

// add pdf attachment in the email

$mail->addStringAttachment($pdf,"myattachment.pdf");

 

Now if we send it we will see a attachment along with the email something like this as shown below.

 

 

 

This completes our tutorial on how to send email along with PDF Attachments using PHP Mailer. Thanks for reading this post.

Leave a Reply

Close Menu

Indian Desi Tools - Ultimate Tools Website

Demo Description


This will close in 20 seconds