Are there best practices for using the mail() function in PHP to ensure secure email handling?

When using the mail() function in PHP, it is important to sanitize user input to prevent email injection attacks. This can be done by validating and filtering user input before passing it to the mail() function. Additionally, it is recommended to set headers properly to prevent header injection attacks and to avoid sending sensitive information in plain text.

// Sanitize user input
$to = filter_var($_POST['to'], FILTER_SANITIZE_EMAIL);
$subject = filter_var($_POST['subject'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

// Set additional headers to prevent header injection
$headers = "From: your_email@example.com\r\n";
$headers .= "Reply-To: your_email@example.com\r\n";
$headers .= "X-Mailer: PHP/" . phpversion();

// Send email
$mailSent = mail($to, $subject, $message, $headers);

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