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

Potential security risks associated with using the mail() function in PHP scripts for sending emails include the possibility of email header injection attacks, where an attacker can inject additional headers into the email to manipulate the email content or redirect the email to a different recipient. To mitigate this risk, it is important to sanitize and validate user input before using it in the mail() function.

$to = 'recipient@example.com';
$subject = 'Test Email';
$message = 'This is a test email';
$headers = 'From: sender@example.com' . "\r\n" .
    'Reply-To: sender@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

// Sanitize and validate user input before using it in the mail() function
$to = filter_var($to, FILTER_SANITIZE_EMAIL);
$subject = filter_var($subject, FILTER_SANITIZE_STRING);
$message = filter_var($message, FILTER_SANITIZE_STRING);

// Send the email using the sanitized input
mail($to, $subject, $message, $headers);