In the context of PHP usage, what are some best practices for troubleshooting and resolving issues related to sending emails through scripts?

Issue: When sending emails through PHP scripts, common issues may arise such as emails not being delivered, marked as spam, or not formatted correctly. To troubleshoot and resolve these issues, ensure that the SMTP settings are correctly configured, the email content is properly formatted, and the email addresses are valid. PHP Code Snippet:

// Example of sending an email using PHP's mail() function
$to = 'recipient@example.com';
$subject = 'Test Email';
$message = 'This is a test email sent from PHP.';
$headers = 'From: sender@example.com' . "\r\n" .
    'Reply-To: sender@example.com' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

// Send email
if (mail($to, $subject, $message, $headers)) {
    echo 'Email sent successfully.';
} else {
    echo 'Failed to send email.';
}