What are the potential pitfalls of using the mail() function in PHP scripts, and how can they be mitigated?

The potential pitfalls of using the mail() function in PHP scripts include vulnerability to email injection attacks, lack of proper error handling, and potential issues with email deliverability. These can be mitigated by sanitizing user input, using proper headers to prevent injection, implementing error checking, and using a reliable mail server.

// Example of mitigating email injection attacks and implementing error handling

$to = 'recipient@example.com';
$subject = 'Test Email';
$message = 'This is a test email';

// Sanitize user input
$to = filter_var($to, FILTER_SANITIZE_EMAIL);

// Set proper headers to prevent injection
$headers = "From: sender@example.com\r\n";
$headers .= "Reply-To: sender@example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=utf-8\r\n";

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