What are the potential consequences of using the mail() function directly for sending form data in PHP?

Using the mail() function directly for sending form data in PHP can lead to security vulnerabilities such as email injection attacks. To prevent this, it is recommended to sanitize and validate user input before using it in the mail() function.

<?php
// Sanitize and validate form data before using the mail() function
$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 email is valid
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    // Send email using the sanitized data
    $to = 'recipient@example.com';
    $subject = 'Contact Form Submission';
    $headers = 'From: ' . $email;

    mail($to, $subject, $message, $headers);
    echo 'Email sent successfully';
} else {
    echo 'Invalid email address';
}
?>