What best practices should be followed when sending emails with attachments in PHP, specifically PDF files?
When sending emails with attachments in PHP, specifically PDF files, it is important to set the appropriate headers and encoding to ensure the attachment is handled correctly by the recipient's email client. Additionally, make sure to specify the content type as "application/pdf" for PDF files and encode the attachment using base64 to ensure compatibility.
// Email variables
$to = 'recipient@example.com';
$subject = 'Attachment Test';
$message = 'Please see the attached PDF file.';
$from = 'sender@example.com';
// Attachment variables
$file_path = 'path/to/your/file.pdf';
$file_name = 'attachment.pdf';
$content = file_get_contents($file_path);
$encoded_content = chunk_split(base64_encode($content));
// Email headers
$headers = "From: $from\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"boundary\"\r\n";
// Email body
$body = "--boundary\r\n";
$body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
$body .= "Content-Transfer-Encoding: 7bit\r\n";
$body .= "\r\n$message\r\n";
$body .= "--boundary\r\n";
$body .= "Content-Type: application/pdf; name=\"$file_name\"\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n";
$body .= "Content-Disposition: attachment; filename=\"$file_name\"\r\n";
$body .= "\r\n$encoded_content\r\n";
$body .= "--boundary--";
// Send email with attachment
if (mail($to, $subject, $body, $headers)) {
echo 'Email sent successfully.';
} else {
echo 'Email sending failed.';
}
Keywords
Related Questions
- How can PHP functions be optimized to avoid unnecessary iterations for each variable?
- What are some best practices for handling database insertions and retrieving IDs in PHP to avoid issues like the one described in the forum thread?
- How can arrays be effectively used in PHP to replace characters in a string, like in the provided code snippet?