What are best practices for handling email sending errors in PHP scripts?

When sending emails in PHP scripts, it is important to handle potential errors that may occur during the sending process. One common practice is to use try-catch blocks to catch any exceptions that may be thrown when sending an email. This allows you to handle the error gracefully and provide feedback to the user if necessary.

try {
    // Attempt to send the email
    $success = mail($to, $subject, $message, $headers);
    
    if(!$success) {
        throw new Exception('Failed to send email');
    }
    
    // Email sent successfully
    echo 'Email sent successfully';
} catch(Exception $e) {
    // Handle the error
    echo 'An error occurred: ' . $e->getMessage();
}