What are the best practices for encoding email subjects in UTF-8 when using PHP to send emails?

When sending emails with PHP, it is important to properly encode email subjects in UTF-8 to ensure that special characters are displayed correctly. To do this, you can use the mb_encode_mimeheader function in PHP to encode the subject line. This function will handle any special characters and ensure that the subject is properly encoded for email clients to display correctly.

$subject = 'Subject with special characters like é and ü';
$subject_encoded = mb_encode_mimeheader($subject, 'UTF-8');

// Send email with encoded subject
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
$headers .= 'From: sender@example.com' . "\r\n";

// Additional headers
$additional_headers = 'Subject: ' . $subject_encoded . "\r\n";

// Send email
mail('recipient@example.com', $subject_encoded, 'Email body content', $headers, $additional_headers);