What is the issue with multipart/remixed-mail saving text as an attachment in PHP?

When saving text as an attachment in multipart/remixed-mail in PHP, the issue is that the text may not be displayed correctly when the email is opened. To solve this issue, you can encode the text using base64 before attaching it to the email.

// Encode text using base64
$text = "This is the text to be attached";
$encoded_text = base64_encode($text);

// Add the attachment to the email
$boundary = md5(uniqid(time()));
$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: base64\r\n\r\n";
$body .= chunk_split($encoded_text)."\r\n";
$body .= "--".$boundary."--";

// Send the email
$to = "recipient@example.com";
$subject = "Test Email with Attachment";
$mail = mail($to, $subject, $body, $headers);

if($mail) {
    echo "Email sent successfully with attachment.";
} else {
    echo "Failed to send email with attachment.";
}