Are there any common pitfalls or mistakes to avoid when using the mail() function in PHP?

One common pitfall when using the mail() function in PHP is not properly sanitizing user input, which can lead to security vulnerabilities like email header injections. To avoid this, always validate and sanitize user input before using it in the mail() function. Another mistake is not handling errors or checking the return value of the mail() function, which can result in emails not being sent successfully. Make sure to check the return value and handle any errors accordingly.

// Sanitize user input before using it in the mail function
$subject = filter_var($_POST['subject'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
$recipient = filter_var($_POST['recipient'], FILTER_SANITIZE_EMAIL);

// Send email and check for errors
if(mail($recipient, $subject, $message)){
    echo "Email sent successfully";
} else {
    echo "Failed to send email";
}