What potential security risks are associated with using the mail() function in PHP for sending emails?

Using the mail() function in PHP for sending emails can pose security risks such as email header injection, allowing malicious users to inject additional headers and potentially execute code. To mitigate this risk, always sanitize user input and validate email addresses before using them in the mail() function.

$to = filter_var($_POST['to'], FILTER_SANITIZE_EMAIL);
$subject = filter_var($_POST['subject'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

// Validate email address
if (filter_var($to, FILTER_VALIDATE_EMAIL)) {
    // Send email
    mail($to, $subject, $message);
} else {
    echo "Invalid email address";
}