How can PHP developers ensure that email headers are RFC-compliant and properly formatted to avoid delivery issues or misinterpretations by email clients?
To ensure that email headers are RFC-compliant and properly formatted, PHP developers should use the `mb_encode_mimeheader()` function to encode non-ASCII characters in headers, and wrap long header lines using the `wordwrap()` function. Additionally, developers should avoid using special characters or control characters in headers to prevent misinterpretations by email clients.
// Example code snippet to ensure RFC-compliant email headers
$subject = 'Subject with non-ASCII characters: こんにちは';
$encoded_subject = mb_encode_mimeheader($subject, 'UTF-8');
$headers = "From: sender@example.com\r\n";
$headers .= "Content-Type: text/plain; charset=UTF-8\r\n";
$headers .= "Subject: " . $encoded_subject . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
// Wrap long header lines to ensure proper formatting
$headers = wordwrap($headers, 70, "\r\n");
// Send email using mail() function
mail('recipient@example.com', 'Test Email', 'This is a test email.', $headers);