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

Using the mail() function in PHP can pose security risks such as email header injection and potential spamming. To mitigate these risks, it is recommended to sanitize user input and validate email addresses before passing them to the mail() function. Additionally, setting proper headers and using a secure email server can help prevent unauthorized access or abuse.

$to = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$subject = "Subject";
$message = "Message";
$headers = "From: yourname@example.com" . "\r\n" .
           "Reply-To: yourname@example.com" . "\r\n" .
           "X-Mailer: PHP/" . phpversion();

// Send email
if (filter_var($to, FILTER_VALIDATE_EMAIL)) {
    mail($to, $subject, $message, $headers);
}