What are the best practices for sending attachments with PHP emails?

When sending attachments with PHP emails, it's important to use the proper MIME type for the attachment and encode the attachment data correctly. This ensures that the attachment is properly handled by email clients and can be opened by the recipient without any issues.

// Example PHP code snippet for sending an email with attachment
$to = 'recipient@example.com';
$subject = 'Email with Attachment';
$message = 'Please see the attached file.';
$filename = 'attachment.pdf';
$file = '/path/to/attachment.pdf';
$content = file_get_contents($file);
$encoded_content = chunk_split(base64_encode($content));

$attachment = "Content-Type: application/pdf; name=\"" . $filename . "\"\r\n";
$attachment .= "Content-Transfer-Encoding: base64\r\n";
$attachment .= "Content-Disposition: attachment; filename=\"" . $filename . "\"\r\n\r\n";
$attachment .= $encoded_content . "\r\n";

$headers = "From: sender@example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"boundary\"\r\n";

$body = "--boundary\r\n";
$body .= "Content-Type: text/plain; charset=\"utf-8\"\r\n";
$body .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$body .= $message . "\r\n";
$body .= "--boundary\r\n";
$body .= $attachment;

mail($to, $subject, $body, $headers);