How can the Pear class be utilized to avoid issues with sending emails in PHP?

The Pear class can be utilized to avoid issues with sending emails in PHP by providing a more robust and reliable email sending functionality compared to the built-in mail() function. Pear offers features such as SMTP authentication, MIME message composition, and error handling, which can help ensure that emails are delivered successfully.

<?php
require_once "Mail.php";

$from = "sender@example.com";
$to = "recipient@example.com";
$subject = "Test email";
$body = "This is a test email.";

$host = "smtp.example.com";
$username = "username";
$password = "password";

$headers = array(
    'From' => $from,
    'To' => $to,
    'Subject' => $subject
);

$smtp = Mail::factory('smtp', array(
    'host' => $host,
    'auth' => true,
    'username' => $username,
    'password' => $password
));

$mail = $smtp->send($to, $headers, $body);

if (PEAR::isError($mail)) {
    echo "Error sending email: " . $mail->getMessage();
} else {
    echo "Email sent successfully!";
}
?>