How can a Mailer class improve the functionality of sending emails through PHP?

Sending emails through PHP can be simplified and improved by creating a Mailer class that encapsulates all the necessary functionality for sending emails. This class can handle tasks such as setting up the email headers, sending the email using a chosen mail transport method (e.g., SMTP or sendmail), and providing error handling for any issues that may arise during the sending process.

class Mailer {
    private $to;
    private $subject;
    private $message;

    public function __construct($to, $subject, $message) {
        $this->to = $to;
        $this->subject = $subject;
        $this->message = $message;
    }

    public function sendEmail() {
        $headers = 'From: your@example.com' . "\r\n" .
                   'Reply-To: your@example.com' . "\r\n" .
                   'X-Mailer: PHP/' . phpversion();

        if (mail($this->to, $this->subject, $this->message, $headers)) {
            echo 'Email sent successfully';
        } else {
            echo 'Email sending failed';
        }
    }
}

// Example of using the Mailer class
$to = 'recipient@example.com';
$subject = 'Test Email';
$message = 'This is a test email sent using the Mailer class';

$mailer = new Mailer($to, $subject, $message);
$mailer->sendEmail();