Skip to content
PHP Logo

What are the best practices for creating and sending PDF documents via email using PHP, especially for individuals with limited experience in web development?

When sending PDF documents via email using PHP, it is important to ensure that the PDF file is properly generated and attached to the email. One of the best practices is to use a library like TCPDF or FPDF to create the PDF file dynamically. Once the PDF file is generated, it can be attached to the email using PHP's built-in mail function or a library like PHPMailer.

php
```php
// Include the TCPDF library
require_once('tcpdf/tcpdf.php');

// Create new PDF document
$pdf = new TCPDF();

// Set document information
$pdf->SetCreator('Your Name');
$pdf->SetAuthor('Your Name');
$pdf->SetTitle('Document Title');
$pdf->SetSubject('Document Subject');

// Add a page to the PDF
$pdf->AddPage();

// Set content
$pdf->SetFont('helvetica', '', 12);
$pdf->Cell(0, 10, 'Hello, World!', 0, 1, 'C');

// Output PDF to a temporary file
$pdfFilePath = 'path/to/temporary/file.pdf';
$pdf->Output($pdfFilePath, 'F');

// Send email with PDF attachment
$to = 'recipient@example.com';
$subject = 'PDF Document';
$message = 'Please find the PDF document attached.';
$from = 'sender@example.com';

// Create a boundary for the email
$boundary = md5(uniqid(time()));

// Set headers
$headers = "From: $from\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n";

// Open the file for reading
$file = fopen($pdfFilePath, 'rb');
$data = fread($file, filesize($pdfFilePath));
fclose($file);

// Encode the file data
$data = chunk_split(base64_encode($data));

// Add attachment to the email
$body = "--$boundary\r\n";
$body .= "Content-Type: application/pdf; name=\"document.pdf\"\r\n";
$body .= "Content-Disposition: attachment; filename=\"document.pdf\"\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n";
$body .= "\r\n";
$body .= $data;
$body .= "\r\n";
$body .= "--$boundary--";

// Send email
$mailSent = mail($to, $subject, $message, $headers, '-f' . $from);

// Delete the temporary PDF file
unlink($pdfFilePath);