What are some best practices for preventing character encoding issues in PHP email headers when sending emails to different recipients?

Character encoding issues in PHP email headers can be prevented by ensuring that the headers are properly encoded using UTF-8. This can be achieved by using the mb_encode_mimeheader() function to encode any non-ASCII characters in the headers before sending the email.

// Set the email headers
$subject = 'Subject with non-ASCII characters: é, ñ, etc.';
$subject = mb_encode_mimeheader($subject, 'UTF-8');

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

// Send the email
$to = 'recipient@example.com';
$message = 'Email content with non-ASCII characters: é, ñ, etc.';
mail($to, $subject, $message, $headers);