What are the potential pitfalls of using email addresses directly in the mail() function in PHP?

Using email addresses directly in the mail() function in PHP can expose your code to email injection attacks. To prevent this, you should sanitize and validate the email addresses before using them in the mail() function. This can be done by using PHP's filter_var() function with the FILTER_VALIDATE_EMAIL filter.

$to = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
if($to){
    // Proceed with sending the email
    mail($to, $subject, $message, $headers);
} else {
    // Handle invalid email address
    echo "Invalid email address";
}