What are the potential risks of 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 and spamming. To mitigate these risks, it is recommended to sanitize user input and validate email addresses before passing them to the mail() function.

// Sanitize and validate email address before using the mail() function
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
    // Send email using the sanitized and validated email address
    mail($email, 'Subject', 'Message');
} else {
    echo 'Invalid email address';
}