What best practices should be followed when setting headers for email messages in PHP scripts?

When setting headers for email messages in PHP scripts, it is important to include necessary headers such as From, Reply-To, and Content-Type to ensure proper delivery and formatting of the email. Additionally, it is recommended to sanitize user input to prevent header injection attacks.

// Set necessary headers for email message
$to = "recipient@example.com";
$subject = "Test Email";
$message = "This is a test email.";

$headers = "From: sender@example.com\r\n";
$headers .= "Reply-To: sender@example.com\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";

// Sanitize user input
$to = filter_var($to, FILTER_SANITIZE_EMAIL);
$subject = filter_var($subject, FILTER_SANITIZE_STRING);
$message = filter_var($message, FILTER_SANITIZE_STRING);

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