How can HTML and text encoding in email headers affect email deliverability in PHP?

HTML and text encoding in email headers can affect email deliverability in PHP by causing emails to be marked as spam or not displayed correctly in the recipient's email client. To solve this issue, it is important to properly encode the email headers using UTF-8 and ensure that both HTML and plain text versions of the email are included in the message.

// Set the email headers with proper encoding
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";

// Create a boundary for the email parts
$boundary = uniqid('np');

// Set the email message with both HTML and plain text versions
$message = "--" . $boundary . "\r\n";
$message .= "Content-type: text/plain;charset=UTF-8" . "\r\n";
$message .= "This is the plain text version of the email." . "\r\n";
$message .= "--" . $boundary . "\r\n";
$message .= "Content-type: text/html;charset=UTF-8" . "\r\n";
$message .= "<html><body><p>This is the HTML version of the email.</p></body></html>" . "\r\n";
$message .= "--" . $boundary . "--";

// Send the email with the properly encoded headers and message
mail($to, $subject, $message, $headers);