What best practices should be followed when creating a PHP form for email submission?

When creating a PHP form for email submission, it is important to sanitize and validate user input to prevent malicious code injection and ensure data integrity. Additionally, use PHP's built-in mail() function to send the email securely. Finally, consider implementing CSRF protection to prevent cross-site request forgery attacks.

<?php

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);

    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $to = "recipient@example.com";
        $subject = "New email submission";
        $message = "Email: " . $email;
        $headers = "From: sender@example.com";

        if (mail($to, $subject, $message, $headers)) {
            echo "Email sent successfully";
        } else {
            echo "Failed to send email";
        }
    } else {
        echo "Invalid email address";
    }
}

?>