Are there best practices for configuring PHP mail function to avoid emails being marked as spam?

When using the PHP mail function, there are several best practices to follow in order to avoid emails being marked as spam. Some of these practices include setting proper headers, ensuring the email content is not flagged as spammy, using a valid sender email address, and authenticating the email server. By following these best practices, you can increase the chances of your emails being delivered successfully.

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

// Additional headers for authentication if required
// $headers .= "X-Mailer: PHP/" . phpversion() . "\r\n";
// $headers .= "X-Originating-IP: " . $_SERVER['SERVER_ADDR'] . "\r\n";

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

if ($mail_sent) {
    echo "Email sent successfully";
} else {
    echo "Failed to send email";
}