What are some best practices for handling encoding and special characters in PHP mail() function to ensure proper delivery of emails?

When using the PHP mail() function to send emails, it is important to properly handle encoding and special characters to ensure that the email is delivered correctly. One common issue is that special characters or non-ASCII characters may not display properly if not encoded correctly. To solve this, you can use the mb_encode_mimeheader() function to encode headers and the mb_encode_mimeheader() or mb_encode_mimeheader() functions to encode the email body.

// Set the email headers
$subject = 'Subject with special characters';
$subject = mb_encode_mimeheader($subject, 'UTF-8');

$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
$headers .= 'From: sender@example.com' . "\r\n";
$headers .= 'Reply-To: sender@example.com' . "\r\n";
$headers .= 'X-Mailer: PHP/' . phpversion();

// Encode the email body
$body = 'Email body with special characters';
$body = mb_encode_mimeheader($body, 'UTF-8');

// Send the email
$to = 'recipient@example.com';
mail($to, $subject, $body, $headers);