What are some best practices for handling email headers in PHP to ensure successful email delivery?

When sending emails in PHP, it's important to properly handle email headers to ensure successful delivery. One common issue is the inclusion of incorrect or malformed headers, which can result in emails being marked as spam or not delivered at all. To address this, make sure to use valid headers and sanitize user input to prevent injection attacks.

// Example of setting proper headers when sending an email in PHP
$to = "recipient@example.com";
$subject = "Test Email";
$message = "This is a test email.";

// Set headers
$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=ISO-8859-1\r\n";

// Send email
mail($to, $subject, $message, $headers);