What are some best practices for error handling and validation when implementing a PHP script to read a file and send its contents via email?

When implementing a PHP script to read a file and send its contents via email, it's important to handle errors and validate inputs to ensure the script runs smoothly. Best practices include checking if the file exists before attempting to read it, validating the email address before sending the email, and handling any potential errors that may occur during the file reading or email sending process.

<?php

// Check if the file exists before reading it
$file = 'example.txt';
if (file_exists($file)) {
    $file_contents = file_get_contents($file);
    
    // Validate the email address before sending the email
    $email = 'recipient@example.com';
    if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $subject = 'File contents';
        
        // Send email with file contents
        $headers = 'From: sender@example.com';
        mail($email, $subject, $file_contents, $headers);
        echo 'Email sent successfully';
    } else {
        echo 'Invalid email address';
    }
} else {
    echo 'File does not exist';
}

?>