<?php
class SMTPMailer {
    private $host;
    private $port;
    private $user;
    private $pass;
    private $debug = false;

    public function __construct($host, $port, $user, $pass) {
        $this->host = $host;
        $this->port = $port;
        $this->user = $user;
        $this->pass = $pass;
    }

    public function send($to, $subject, $message, $from_name, $from_email, $is_html = false) {
        $content_type = $is_html ? "text/html" : "text/plain";
        
        $header = "From: \"$from_name\" <$from_email>\r\n";
        $header .= "Reply-To: $from_email\r\n";
        $header .= "To: $to\r\n";
        $header .= "Subject: $subject\r\n";
        $header .= "Content-Type: $content_type; charset=\"utf-8\"\r\n";
        $header .= "Content-Transfer-Encoding: 8bit\r\n";
        $header .= "MIME-Version: 1.0\r\n";
        $header .= "Date: " . date('r') . "\r\n";
        $header .= "\r\n";

        $socket = fsockopen("ssl://" . $this->host, $this->port, $errno, $errstr, 30);
        if (!$socket) {
            return "Could not connect to SMTP host: $errstr ($errno)";
        }

        $this->getServerResponse($socket);

        fputs($socket, "EHLO " . $this->host . "\r\n");
        $this->getServerResponse($socket);

        fputs($socket, "AUTH LOGIN\r\n");
        $this->getServerResponse($socket);

        fputs($socket, base64_encode($this->user) . "\r\n");
        $this->getServerResponse($socket);

        fputs($socket, base64_encode($this->pass) . "\r\n");
        $this->getServerResponse($socket);

        fputs($socket, "MAIL FROM: <{$this->user}>\r\n");
        $this->getServerResponse($socket);

        fputs($socket, "RCPT TO: <$to>\r\n");
        $this->getServerResponse($socket);

        fputs($socket, "DATA\r\n");
        $this->getServerResponse($socket);

        fputs($socket, $header . $message . "\r\n.\r\n");
        $this->getServerResponse($socket);

        fputs($socket, "QUIT\r\n");
        $this->getServerResponse($socket);

        fclose($socket);
        return true;
    }

    private function getServerResponse($socket) {
        $response = "";
        while ($str = fgets($socket, 515)) {
            $response .= $str;
            if (substr($str, 3, 1) == " ") break;
        }
        return $response;
    }
}
?>
