How can the PHP mail() function be modified to throw errors when incorrect data is passed?

The PHP mail() function does not throw errors when incorrect data is passed, making it difficult to troubleshoot issues with sending emails. To address this, we can modify the code to check for errors and handle them accordingly. One way to achieve this is by using the return value of the mail() function to determine if the email was sent successfully or not.

// Modify the PHP mail() function to throw errors when incorrect data is passed

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

if(mail($to, $subject, $message)) {
    echo 'Email sent successfully';
} else {
    echo 'Failed to send email';
}