Are there any potential pitfalls to be aware of when using the mail() function in PHP scripts?

One potential pitfall when using the mail() function in PHP scripts is the vulnerability to email header injection attacks. To prevent this, always sanitize user input before using it in the headers of the email. This can be done by validating and filtering the input to ensure it does not contain any malicious characters.

// Sanitize email input to prevent header injection
$to = filter_var($_POST['to'], FILTER_SANITIZE_EMAIL);
$subject = filter_var($_POST['subject'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);

// Send sanitized email using mail() function
mail($to, $subject, $message);