What best practices should be followed when sending emails with PHP, especially in terms of email headers and user input validation?

When sending emails with PHP, it is important to properly set email headers to prevent issues such as emails being marked as spam. Additionally, user input validation should be implemented to ensure that the input data is safe and does not contain malicious content.

// Set email headers
$to = "recipient@example.com";
$subject = "Subject of the email";
$message = "Body of the email";

$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";

// Validate user input
if(filter_var($to, FILTER_VALIDATE_EMAIL) && !empty($subject) && !empty($message)){
    // Send the email
    mail($to, $subject, $message, $headers);
} else {
    echo "Invalid input data";
}