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

When handling email sending functionality in PHP scripts, it is important to ensure proper error handling, validation of user input, and secure handling of sensitive information such as email addresses and passwords. Additionally, using a reliable email library or service provider can help streamline the process and improve deliverability rates.

// Example of sending an email using PHP's built-in mail function

$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.";
}