Send PDF file as attachment using php mailer

32 views Asked by At

i want when a user clicks on the button a pdf is generated "not downloaded" and sent to the email of the current logged in user unless the the user is not using an email then download

this is my sample code, am able to grab the email and send if there is no attachment, i don't what wrong if its the way am generating file

function exportPDF(imageUrl) {

    window.jsPDF = window.jspdf.jsPDF;
    var pdf = new jsPDF('p', 'pt', 'a4');


    var img = new Image();
    img.crossOrigin = "Anonymous"; // Allow loading images from different domains
    img.onload = function() {
        // Calculate the width and height of the image to fit within the PDF page
        var pdfWidth = pdf.internal.pageSize.getWidth();
        var pdfHeight = pdf.internal.pageSize.getHeight();
        var imgWidth = this.width;
        var imgHeight = this.height;
        var scaleFactor = Math.min(pdfWidth / imgWidth, pdfHeight / imgHeight);


        var scaledWidth = imgWidth * scaleFactor;
        var scaledHeight = imgHeight * scaleFactor;

        pdf.addImage(this, 'JPEG', 0, 0, scaledWidth, scaledHeight, undefined, 'SLOW'); // 'SLOW' compression for higher quality

        var currentUserEmail = document.getElementById("username").textContent.trim();

        // Validate the email address
        const validateEmail = (email) => {
            return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
        };


        // Check if the email is valid
        var isEmailValid = validateEmail(currentUserEmail);
        console.log('isEmailValid:', isEmailValid);

        if(isEmailValid) {
            
            var attachment = pdf.output('blob');

            send_email(currentUserEmail);

            } else {

            // Download the PDF to the device
            pdf.save(candidateExam_No + ".pdf");
        }
    };

    // Set the image source
    img.src = imageUrl;
}

//then send the email using using and php mailer

function send_email(email) {
        var formData = new FormData();
        formData.append('attachment', attachment);
        formData.append('email', email);



    $.ajax({
        url: 'includes/send_email.php',
        method: 'POST',
        processData: false,
        contentType: false,
        data: formData,
        dataType: 'json',
        success: function(data) {
            if(data.status == '200') {
                Swal.fire({
                    text: data.response_msg,
                    showConfirmButton: true,
                    color: "#ffffff",
                    background: "#039567",
                    width: 320,
                    confirmButtonText: 'OK!'
                });
            } else {
                Swal.fire({
                    text: data.response_msg,
                    showConfirmButton: true,
                    color: "#ffffff",
                    background: "#039567",
                    width: 320,
                    cancelButtonColor: '#3085d6',
                    confirmButtonText: 'OK!'
                });
            }
        }
    });

on the server side am using phpmailer

<?php

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

require '../../PHPMailer/src/Exception.php';
require '../../PHPMailer/src/PHPMailer.php';
require '../../PHPMailer/src/SMTP.php';
header("Content-Type:application/json; charset=utf-8");
$data_array = array();

if( isset($_POST['attachment']) && isset($_POST['email'])) {
    
    $attachment = $_POST['attachment'];
    $email = $_POST['email'];
    
    $file_path = $attachment; 

    try {

        $mail = new PHPMailer(true);
        
        $mail->isSMTP();                                            //Send using SMTP
        $mail->Host       = 'smtp.gmail.com';                     //Set the SMTP server to send through
        $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
        $mail->Username   = 'username';                     //SMTP username
        $mail->Password   = 'password';                               //SMTP password
        $mail->SMTPSecure = 'tls';
        $mail->Port       = 587;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`


        $mail->setFrom('[email protected]');
        $mail->addAddress($email);
        //Attachments
        // $mail->addAttachment($file_path); 
    
        //Content
        $mail->isHTML(true);                                  //Set email format to HTML
        $mail->Subject = 'Certificate';
        $mail->Body    = 'Dear sir / madam <br /><br /> Attached to this email, is your certificate. Please review it carefully to ensure that all information is accurate and complete. If you have any corrections or concerns regarding the certificate, please don\'t hesitate to reach out to us<br /><br />';
        $mail->AltBody = 'Dear sir / madam <br /><br /> Attached to this email, is your certificate. Please review it carefully to ensure that all information is accurate and complete. If you have any corrections or concerns regarding the certificate, please don\'t hesitate to reach out to us<br /><br />';
        $mail->send();

        $data_array['status'] = '200';
        $data_array['response_msg'] = 'certificate sent to '.$email.' sucessfully';

        // unlink($file_path);

    } catch (Exception $e) {
        $data_array['status'] = '400';
        $data_array['response_msg'] = 'Message could not be sent. Mailer Error: '.$mail->ErrorInfo;
    }

}else{
    $data_array['status'] = '400';
    $data_array['response_msg'] = 'Attachment or email not set';
}
echo json_encode($data_array);
?>
0

There are 0 answers