What best practices should be followed when using the mail() function in PHP to ensure successful email delivery?
When using the mail() function in PHP to send emails, it is important to follow best practices to ensure successful email delivery. This includes properly setting the headers, ensuring the email addresses are valid, and handling any potential errors that may occur during the sending process.
$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";
if (mail($to, $subject, $message, $headers)) {
echo "Email sent successfully.";
} else {
echo "Email sending failed.";
}