What are the best practices for handling mailing functions in PHP scripts?

When handling mailing functions in PHP scripts, it is important to ensure proper error handling, use secure methods for sending emails, and sanitize user input to prevent injection attacks.

// 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 sent from PHP.";
$headers = "From: sender@example.com";

if (mail($to, $subject, $message, $headers)) {
    echo "Email sent successfully.";
} else {
    echo "Email sending failed.";
}