How can PHP's mail() function be used to send form data via email?

To send form data via email using PHP's mail() function, you need to collect the form data using $_POST or $_GET, then construct the email message with the form data included, 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 = "Form Submission";
    $body = "Name: $name\nEmail: $email\nMessage: $message";
    
    if (mail($to, $subject, $body)) {
        echo "Email sent successfully!";
    } else {
        echo "Email sending failed.";
    }
}
?>