Reputation: 163
I am trying to create a PDF with the FPDF Library and send it via the WordPress wp_mail function to a specific email address. Important: I don't want to save the file first on my server.
There are many threads and websites, but none of the solutions worked for me.
At the moment I have the following code:
$email = '[email protected]';
$subject = 'Test attachment';
$body = 'This is the body text.';
$separator = md5(time());
$headers = "MIME-Version: 1.0";
$headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"";
$headers .= "Content-Transfer-Encoding: 7bit";
$pdfdoc = $pdf->Output("test.pdf", "S");
$attachment = chunk_split(base64_encode($pdfdoc));
wp_mail( $email, $subject, $body, $headers, $attachment );
I get an email without attachment. I have also tried:
$pdfdoc = $pdf->Output("test.pdf", "S");
$attachment = array( chunk_split(base64_encode($pdfdoc)));
wp_mail( $email, $subject, $body, $headers, $attachment );
If I attach an image from my server, the file will be attached with the following code and is working fine:
$attachment = array( $_SERVER['DOCUMENT_ROOT'] . '/path/to/file/image.png' );
wp_mail( $email, $subject, $body, $headers, $attachment );
So my only problem is how to generate and attach the PDF file to the email.
Thank you very much.
Upvotes: 2
Views: 1724
Reputation: 31
I had the same issue, and I solved it by temporarily saving the file on the server and then deleting it after the email has been send. Works like a charm.
Here is the working code :
$email = '[email protected]';
$subject = 'Test attachment';
$body = 'This is the body text.';
$separator = md5(time());
$headers = "MIME-Version: 1.0";
$headers .= "Content-Type: multipart/mixed; boundary=\"".$separator."\"";
$headers .= "Content-Transfer-Encoding: 7bit";
$filename = __DIR__ . "test.pdf"; // You specify the path for the file
$pdf->Output($filename, "F"); // "F" is for saving the file on the server
$attachment = array($filename);
wp_mail( $email, $subject, $body, $headers, $attachment );
unlink($filename); // Deletion of the created file.
Upvotes: 3