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

Using the raw PHP mail() function can pose security risks such as email header injection and potential for spamming. To mitigate these risks, it is recommended to sanitize user input and validate email addresses before using the mail() function.

// Sanitize and validate email address before sending email
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $subject = "Subject";
    $message = "Message";
    $headers = "From: sender@example.com" . "\r\n" .
               "Reply-To: sender@example.com" . "\r\n" .
               "X-Mailer: PHP/" . phpversion();

    // Send email
    mail($email, $subject, $message, $headers);
}