How can the PHP code be optimized to ensure that emails are only sent when all input fields are correctly filled out?

To ensure that emails are only sent when all input fields are correctly filled out, we can add validation checks to each input field before attempting to send the email. This can be done by checking if each input field is not empty or if it meets certain criteria (e.g. valid email format). If any input field fails the validation, we can display an error message and prevent the email from being sent.

<?php
if(isset($_POST['submit'])){
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];

    // Check if all input fields are filled out
    if(!empty($name) && !empty($email) && !empty($message)){
        // Additional validation checks can be added here (e.g. email format)
        
        // Send the email
        $to = "recipient@example.com";
        $subject = "New message from $name";
        $body = "Name: $name\nEmail: $email\nMessage: $message";
        mail($to, $subject, $body);

        echo "Email sent successfully!";
    } else {
        echo "Please fill out all the required fields.";
    }
}
?>