What are some potential pitfalls to avoid when working with encoding and special characters in PHP mail() function to prevent issues like garbled text in emails?

When working with encoding and special characters in the PHP mail() function, it's important to ensure that the content of the email is properly encoded to prevent issues like garbled text. One way to solve this is by using the mb_encode_mimeheader() function to encode the subject line of the email and mb_encode_mimeheader() or mb_encode_mimeheader() to encode the body of the email.

$subject = 'Subject with special characters';
$subject = mb_encode_mimeheader($subject, 'UTF-8');

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

$headers = 'From: sender@example.com' . "\r\n" .
           'MIME-Version: 1.0' . "\r\n" .
           'Content-type: text/html; charset=UTF-8' . "\r\n" .
           'Content-Transfer-Encoding: 8bit' . "\r\n";

mail('recipient@example.com', $subject, $body, $headers);