How can the use of PHP mail function be optimized to ensure successful delivery to major email providers?

The PHP mail function can be optimized for successful delivery to major email providers by setting proper headers, including a valid "From" address, adding SPF and DKIM records to your domain, and avoiding sending bulk emails from a shared hosting server. By following these best practices, you can increase the chances of your emails being delivered successfully.

$to = "recipient@example.com";
$subject = "Subject of the email";
$message = "This is the body of the email.";

$headers = "From: yourname@example.com\r\n";
$headers .= "Reply-To: yourname@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 SPF and DKIM records
$headers .= "Return-Path: yourname@example.com\r\n";
$headers .= "X-Sender: yourname@example.com\r\n";
$headers .= "X-Mailer: PHP\r\n";
$headers .= "X-Priority: 1\r\n";

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