How can the mail() function be integrated into a PHP script to send form data to a specified email address?

To send form data to a specified email address using the mail() function in PHP, you need to set the appropriate headers, such as From, Reply-To, and Content-Type. Additionally, you need to sanitize and validate the form data to prevent security vulnerabilities. Finally, call the mail() function with the recipient email address, subject, message, and headers to send the email.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];

    // Sanitize and validate form data

    $to = "recipient@example.com";
    $subject = "Contact Form Submission";
    $headers = "From: $email\r\n";
    $headers .= "Reply-To: $email\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

    $body = "Name: $name <br>";
    $body .= "Email: $email <br>";
    $body .= "Message: $message";

    if (mail($to, $subject, $body, $headers)) {
        echo "Email sent successfully!";
    } else {
        echo "Failed to send email. Please try again.";
    }
}
?>