How can the PHP code be improved to ensure proper email sending functionality?

To ensure proper email sending functionality in PHP, it is important to validate the email address, set appropriate headers, and handle any potential errors that may occur during the sending process. Additionally, using a reliable email service provider or SMTP server can help improve deliverability.

<?php
$to = 'recipient@example.com';
$subject = 'Test Email';
$message = 'This is a test email.';
$headers = 'From: sender@example.com' . "\r\n" .
    'Reply-To: sender@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

if (filter_var($to, FILTER_VALIDATE_EMAIL)) {
    if (mail($to, $subject, $message, $headers)) {
        echo 'Email sent successfully';
    } else {
        echo 'Failed to send email';
    }
} else {
    echo 'Invalid email address';
}
?>