<?php
if(!(is_readable(realpath(dirname(__FILE__)).'/log.inc'))) {
	die('Error - Could not open or read file '.realpath(dirname(__FILE__)).'/log.inc');
} else {
	include_once(realpath(dirname(__FILE__)).'/log.inc');
}

$config['smtp_username'] = getSetting('smtp','username','');
$config['smtp_port']     = getSetting('smtp','port','');
$config['smtp_host']     = getSetting('smtp','host','');
$config['smtp_password'] = getSetting('smtp','password','');
$config['smtp_login']     = getSetting('smtp','login','');
$config['smtp_from']     = getSetting('smtp','from','');
$config['smtp_debug']    = false;
$config['smtp_charset']  = 'utf-8';   //кодировка сообщений. (или UTF-8, итд)

function smtpmail($mail_to, $subject, $message,  $username = '[not transmitted]', $headers='') {
        global $config;
        $SEND = "Date: ".date("D, d M Y H:i:s O") . "\r\n";
        $SEND .=   'Subject: =?'.$config['smtp_charset'].'?B?'.base64_encode($subject)."=?=\r\n";
        if ($headers) $SEND .= $headers."\r\n\r\n";
        else
        {
                $SEND .= "Reply-To: ".$config['smtp_username']."\r\n";
                $SEND .= "MIME-Version: 1.0\r\n";
                $SEND .= "Content-Type: text/html; charset=\"".$config['smtp_charset']."\"\r\n";
                $SEND .= "Content-Transfer-Encoding: 8bit\r\n";
                $SEND .= "From: \"".$config['smtp_from']."\" <".$config['smtp_username'].">\r\n";
                /* старый вариант $SEND .= "To: $mail_to <$mail_to>\r\n";
                   чтобы посылать в виде ИМЯ <АДРЕС> надо экранировать имя кавычками, например, так $SEND .= "To: \"".$mail_to."\"<".$mail_to.">\r\n";
                   но так как у нас нет отображаемого имени, то можно и просто:
                */
                $SEND .= "To: $mail_to\r\n";
                $SEND .= "X-Priority: 3\r\n\r\n";
        }
        $SEND .=  $message."\r\n";
         if( !$socket = fsockopen($config['smtp_host'], $config['smtp_port'], $errno, $errstr, 30) ) {
         	if ($config['smtp_debug']) echo $errno."&lt;br&gt;".$errstr;
            return false;
         }

        if (!server_parse($socket, "220", __LINE__)) return false;

        fputs($socket, "HELO " . $config['smtp_host'] . "\r\n");
        if (!server_parse($socket, "250", __LINE__)) {
           logmailevent('mail.inc Failed send HELO!');
           fclose($socket);
           return false;
        }

        fputs($socket, "AUTH LOGIN\r\n");
        if (!server_parse($socket, "334", __LINE__)) {
           logmailevent('mail.inc Failed to find answer to authorization request.');
           fclose($socket);
           return false;
        }

        fputs($socket, base64_encode($config['smtp_login']) . "\r\n");
        if (!server_parse($socket, "334", __LINE__)) {
           logmailevent('mail.inc Authorization login not accepted by the server!');
           fclose($socket);
           return false;
        }

        fputs($socket, base64_encode($config['smtp_password']) . "\r\n");
        if (!server_parse($socket, "235", __LINE__)) {
           logmailevent('mail.inc Password is invalid, not accepted by the server! Authorization Error!');
           fclose($socket);
           return false;
        }

        fputs($socket, "MAIL FROM: <".$config['smtp_username'].">\r\n");
        if (!server_parse($socket, "250", __LINE__)) {
           logmailevent('mail.inc Failed send a command MAIL FROM: ');
           fclose($socket);
           return false;
        }

        fputs($socket, "RCPT TO: <" . $mail_to . ">\r\n");
        if (!server_parse($socket, "250", __LINE__)) {
           logmailevent('Email not set for user '.$username);
           fclose($socket);
           return false;
        }
        fputs($socket, "DATA\r\n");
        if (!server_parse($socket, "354", __LINE__)) {
           logmailevent('mail.inc Failed send a command DATA');
           fclose($socket);
           return false;
        }

        fputs($socket, $SEND."\r\n.\r\n");
        if (!server_parse($socket, "250", __LINE__)) {
           logmailevent('mail.inc Failed to send email body. Email not sent!');
           fclose($socket);
           return false;
        }

        fputs($socket, "QUIT\r\n");
        fclose($socket);
        logmailevent('mail.inc Email sent successfully to '.$mail_to.' with the '.$subject.' subject and the following body: '.PHP_EOL.' '.$message.' '.PHP_EOL.'');
        return TRUE;
}
function server_parse($socket, $response, $line = __LINE__) {
	global $config;
	$server_response = '';
    while (substr($server_response, 3, 1) != ' ') {
        if (!($server_response = fgets($socket, 256))) {
                   logmailevent('mail.inc Errors sending email! '.$response.' '.$line.'');
                   return false;
                }
    }
    if (substr($server_response, 0, 3) != $response) {
           logmailevent('mail.inc Errors sending email! '.$server_response.' '.$line.' ');
           return false;
        }
    return true;
}


?>
