I am using FPDF and Phpmailer to generate a PDF file and sending it as an email attachment.
My script for PDF generation and phpmailer are working perfectly when I use them as independent scripts.
Now, when I combine both scripts to generate and display the PDF form (without saving it to to the filesystem) and send this PDF document as an attachment, it is not working thouht it generates the PDF and display it on browser, but does not sent it by mail.
My code is:
<?php declare(strict_types=1); use PHPMailerPHPMailerPHPMailer; require 'vendor/autoload.php'; $pdf = new mypdf(); $pdf->AliasNbPages(); $pdf->AddPage('P', 'A4', 0); $pdf->Header(); $pdf->headerTable(); $pdf->viewTable(); $pdf->footer(); $pdf->setMargins(20, 20, 20); $pdf->output(); $pdfString = $pdf->output(); $mail = new PHPMailer; // getting post values $first_name = $_POST['fname']; $to_email = "receipent@gmail.com"; $subject = "stationery issued"; $message = "Dear sir your requested stationery has been issued by Stationery store "; $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = 'sender@gmail.com'; // SMTP username $mail->Password = 'password'; // SMTP password $mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted $mail->Port = 25; // TCP port to connect to $mail->setFrom('sender@gmail.com', 'Your_Name'); $mail->addReplyTo('sender@gmail.com', 'Your_Name'); $mail->addAddress($to_email); // Add a recipient $mail->addStringAttachment((string)$pdfString, 'name file.pdf'); $mail->isHTML(true); // Set email format to HTML $mail->Subject = $subject; $mail->Body = 'Dear ' . $first_name . '<p>' . $message . '</p>'; $mail->send();
Advertisement
Answer
You have left unclear which Phpmailer version you’re using and which FPDF version, therefore it is hard to say what the error exactly is.
On first glance this hit my attention:
$pdfString = $pdf->output();
If the intend is to have $pdf->output()
to return a string, then the invocation looks wrong to me.
That is because the invocation as $pdf->output()
is doing the default output, which is sending to the browser.
Which you said is working, and that is already the line above:
$pdf->output(); $pdfString = $pdf->output();
PHP is an imperative language, that means, it does not make a difference to the method call whether or not you assign a variable to the return value.
So both method calls will behave the same:
$pdf->output(); $pdfString = $pdf->output();
It’s like writing
$pdf->output(); $pdf->output();
Perhaps just an oversight in the heat of the debugging. For debugging, check the preconditions early, verify your script step-by-step. Don’t ask longer than five minutes. Just verify then.
Potential fix:
$pdfString = $pdf->output('S');
may do it, better check with the documentation you have at hand for your version in use.