How can one ensure that parameters passed in the mail() function in PHP are correctly formatted to avoid any issues with email delivery?

To ensure that parameters passed in the mail() function in PHP are correctly formatted for email delivery, it is important to properly set the headers, including the "From" address, subject, and additional headers if needed. Make sure to sanitize user input to prevent header injections and correctly format email addresses. Additionally, check for any potential errors or issues with the email sending process to ensure successful delivery.

$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 .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";

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

// Send the email
if (mail($to, $subject, $message, $headers)) {
    echo "Email sent successfully.";
} else {
    echo "Email delivery failed.";
}