How can error handling be improved in the PHP code to provide more informative messages for troubleshooting email sending problems?

When troubleshooting email sending problems in PHP, it's important to improve error handling to provide more informative messages. One way to achieve this is by using try-catch blocks to catch exceptions thrown during the email sending process. By catching and logging these exceptions, you can easily identify the root cause of the issue and provide more detailed error messages for troubleshooting.

try {
    // Attempt to send the email
    if (!mail($to, $subject, $message, $headers)) {
        throw new Exception('Failed to send email.');
    }
    echo 'Email sent successfully';
} catch (Exception $e) {
    // Log the error message for troubleshooting
    error_log('Error sending email: ' . $e->getMessage());
    echo 'An error occurred while sending the email. Please try again later.';
}