How can the use of the mail() function in PHP scripts be optimized to ensure successful email delivery and avoid common errors like missing headers or incorrect variables?

To optimize the use of the mail() function in PHP scripts and avoid common errors like missing headers or incorrect variables, it is essential to ensure that all necessary headers are included in the email function call. This includes headers like From, Reply-To, and Content-Type. Additionally, make sure that variables used in the email content are properly sanitized and validated to prevent injection attacks.

$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/plain; charset=UTF-8\r\n";

// Sanitize and validate variables here

mail($to, $subject, $message, $headers);