What could be causing the "500 - Internal Server Error" when attaching a file to the PHP mail script?

The "500 - Internal Server Error" when attaching a file to the PHP mail script could be caused by incorrect file permissions, exceeding server limits on file size or execution time, or a syntax error in the code. To solve this issue, check the file permissions, adjust server settings if necessary, and ensure that the code for attaching the file is correctly implemented.

<?php
$to = "recipient@example.com";
$subject = "Email with attachment";
$message = "This is a test email with attachment.";
$from = "sender@example.com";
$filename = "attachment.pdf";
$file = "/path/to/attachment.pdf";
$content = file_get_contents($file);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$headers = "From: ".$from."\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$headers .= "This is a multi-part message in MIME format.\r\n";
$headers .= "--".$uid."\r\n";
$headers .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$headers .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$headers .= $message."\r\n\r\n";
$headers .= "--".$uid."\r\n";
$headers .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n";
$headers .= "Content-Transfer-Encoding: base64\r\n";
$headers .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$headers .= $content."\r\n\r\n";
$headers .= "--".$uid."--";
if (mail($to, $subject, "", $headers)) {
    echo "Email sent successfully with attachment.";
} else {
    echo "Failed to send email with attachment.";
}
?>