What is the purpose of using the mail() function in PHP and what are some best practices for sending emails within a script?

The mail() function in PHP is used to send emails from a script. Some best practices for sending emails within a script include validating user input, sanitizing input to prevent injection attacks, using proper headers to prevent email spoofing, and handling errors gracefully.

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

if(mail($to, $subject, $message, $headers)){
    echo "Email sent successfully.";
} else{
    echo "Email sending failed.";
}