What are the best practices for incorporating user input from HTML forms into PHP email scripts to ensure all necessary information is included in the email?

When incorporating user input from HTML forms into PHP email scripts, it is important to validate and sanitize the input to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. Additionally, ensure that all necessary form fields are included in the email by checking for their presence before sending the email.

<?php
// Validate and sanitize user input
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

// Check if all necessary fields are filled out
if(!empty($name) && !empty($email) && !empty($message)) {
    // Construct email message
    $to = "recipient@example.com";
    $subject = "New message from $name";
    $body = "Name: $name\n";
    $body .= "Email: $email\n";
    $body .= "Message: $message\n";

    // Send email
    if(mail($to, $subject, $body)) {
        echo "Email sent successfully";
    } else {
        echo "Failed to send email";
    }
} else {
    echo "Please fill out all required fields";
}
?>