How can one ensure the security and integrity of a PHP form mailer script?

To ensure the security and integrity of a PHP form mailer script, you should sanitize and validate user input to prevent SQL injection, cross-site scripting, and other malicious attacks. Additionally, use PHP's built-in mail() function to send emails securely and avoid storing sensitive information in the script.

<?php
// Sanitize and validate user input
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

// Send email securely using PHP's mail() function
$to = 'recipient@example.com';
$subject = 'Contact Form Submission';
$headers = 'From: ' . $email;
$body = 'Name: ' . $name . '\nEmail: ' . $email . '\nMessage: ' . $message;

// Send email
if(mail($to, $subject, $body, $headers)) {
    echo 'Email sent successfully';
} else {
    echo 'Email could not be sent';
}
?>