Are there best practices for handling errors related to SMTP servers when using the mail() function in PHP?

When using the mail() function in PHP to send emails, it's important to handle errors related to SMTP servers properly. One common issue is when the SMTP server is unreachable or the email fails to send for some reason. To handle these errors, you can use the return value of the mail() function to check if the email was sent successfully or not.

// Send email
$to = "recipient@example.com";
$subject = "Test Email";
$message = "This is a test email.";
$headers = "From: sender@example.com";

if (mail($to, $subject, $message, $headers)) {
    echo "Email sent successfully.";
} else {
    echo "Failed to send email. Please try again later.";
}