How can the mail() function in PHP be utilized to send form input via email?

To send form input via email using the mail() function in PHP, you need to gather the form data using $_POST or $_GET, then construct the email message using this data, and finally use the mail() function to send the email to the desired recipient.

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];
    
    $to = 'recipient@example.com';
    $subject = 'New form submission';
    $body = "Name: $name\nEmail: $email\nMessage: $message";
    $headers = 'From: sender@example.com';
    
    if (mail($to, $subject, $body, $headers)) {
        echo 'Email sent successfully!';
    } else {
        echo 'Error sending email.';
    }
}
?>