<?php
/**
 * ReOS is a vertical software for real estates.
 * Copyright 2010 IT ELAZOS S.L.
 *
 * This file is part of ReOS v2.x.x.
 *
 * ReOS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * ReOS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with ReOS.  If not, see <http://www.gnu.org/licenses/>.
 **/

/**
 * Sends emails by SMTP or php mail function
 * @author   IT Elazos SL
 * @version  1.0
 * @package  eMailing
 */
require_once('class.phpmailer.php');
$mail             = new PHPMailer();

class smtp_class
{
	var $user=_MAIL_USER;
	var $realm="";
	var $password=_MAIL_PWD;
	var $host_name=_SMTP_HOST;
	var $host_port=25;
	var $localhost="";
	var $timeout=10;
	var $data_timeout=0;
	var $direct_delivery=0;
	var $error="";
	var $debug=0;
	var $html_debug=0;
	var $esmtp=1;
	var $esmtp_host="";
	var $esmtp_extensions=array();
	var $maximum_piped_recipients=100;
	var $exclude_address="";
	var $getmxrr="GetMXRR";
	var $pop3_auth_host="";
	var $pop3_auth_port=110;
	var $type=0; // if 0 uses smtp, if 1 uses php mail function.
	var $head = null;

	/* private variables - DO NOT ACCESS */

	var $state="Disconnected";
	var $connection=0;
	var $pending_recipients=0;
	var $next_token="";
	var $direct_sender="";
	var $connected_domain="";


	/**
	 * Enter description here...
	 *
	 * @param unknown_type $string
	 * @param unknown_type $separator
	 * @return unknown
	 */
	Function Tokenize($string,$separator="")
	{
		if(!strcmp($separator,""))
		{
			$separator=$string;
			$string=$this->next_token;
		}
		for($character=0;$character<strlen($separator);$character++)
		{
			if(GetType($position=strpos($string,$separator[$character]))=="integer")
			$found=(IsSet($found) ? min($found,$position) : $position);
		}
		if(IsSet($found))
		{
			$this->next_token=substr($string,$found+1);
			return(substr($string,0,$found));
		}
		else
		{
			$this->next_token="";
			return($string);
		}
	}
	/**
	 * Enter description here...
	 *
	 * @param unknown_type $message
	 */
	Function OutputDebug($message)
	{
		$message.="\n";
		if($this->html_debug)
		$message=str_replace("\n","<br />\n",HtmlEntities($message));
		echo $message;
		flush();
	}
	/**
	 * Enter description here...
	 *
	 * @param unknown_type $error
	 */
	Function SetDataAccessError($error)
	{
		$this->error=$error;
		if(function_exists("socket_get_status"))
		{
			$status=socket_get_status($this->connection);
			if($status["timed_out"])
			$this->error.=": data access time out";
			elseif($status["eof"])
			$this->error.=": the server disconnected";
		}
	}
	/**
	 * Enter description here...
	 *
	 * @return unknown
	 */
	Function GetLine()
	{
		for($line="";;)
		{
			if(feof($this->connection))
			{
				$this->error="reached the end of data while reading from the SMTP server conection";
				return("");
			}
			if(GetType($data=fgets($this->connection,100))!="string"
			|| strlen($data)==0)
			{
				$this->SetDataAccessError("it was not possible to read line from the SMTP server");
				return("");
			}
			$line.=$data;
			$length=strlen($line);
			if($length>=2
			&& substr($line,$length-2,2)=="\r\n")
			{
				$line=substr($line,0,$length-2);
				if($this->debug)
				$this->OutputDebug("S $line");
				return($line);
			}
		}
	}
	/**
	 * Enter description here...
	 *
	 * @param unknown_type $line
	 * @return unknown
	 */
	Function PutLine($line)
	{
		if($this->debug)
		$this->OutputDebug("C $line");
		if(!fputs($this->connection,"$line\r\n"))
		{
			$this->SetDataAccessError("it was not possible to send a line to the SMTP server");
			return(0);
		}
		return(1);
	}
	/**
	 * Enter description here...
	 *
	 * @param unknown_type $data
	 * @return unknown
	 */
	Function PutData(&$data)
	{
		if(strlen($data))
		{
			if($this->debug)
			$this->OutputDebug("C $data");
			if(!fputs($this->connection,$data))
			{
				$this->SetDataAccessError("it was not possible to send data to the SMTP server");
				return(0);
			}
		}
		return(1);
	}
	/**
	 * Enter description here...
	 *
	 * @param unknown_type $code
	 * @param unknown_type $responses
	 * @return unknown
	 */
	Function VerifyResultLines($code,&$responses)
	{
		$responses=array();
		Unset($match_code);
		while(strlen($line=$this->GetLine($this->connection)))
		{
			if(IsSet($match_code))
			{
				if(strcmp($this->Tokenize($line," -"),$match_code))
				{
					$this->error=$line;
					return(0);
				}
			}
			else
			{
				$match_code=$this->Tokenize($line," -");
				if(GetType($code)=="array")
				{
					for($codes=0;$codes<count($code) && strcmp($match_code,$code[$codes]);$codes++);
					if($codes>=count($code))
					{
						$this->error=$line;
						return(0);
					}
				}
				else
				{
					if(strcmp($match_code,$code))
					{
						$this->error=$line;
						return(0);
					}
				}
			}
			$responses[]=$this->Tokenize("");
			if(!strcmp($match_code,$this->Tokenize($line," ")))
			return(1);
		}
		return(-1);
	}
	/**
	 * Enter description here...
	 *
	 * @return unknown
	 */
	Function FlushRecipients()
	{
		if($this->pending_sender)
		{
			if($this->VerifyResultLines("250",$responses)<=0)
			return(0);
			$this->pending_sender=0;
		}
		for(;$this->pending_recipients;$this->pending_recipients--)
		{
			if($this->VerifyResultLines(array("250","251"),$responses)<=0)
			return(0);
		}
		return(1);
	}

	/*
	 * Method:                TryAuthPlain
	 * Parameters:        $s_data        the data to use for authentication
	 * Returns:                int                1 on success, 0 on failure
	 * Author:                Russell Robinson, 25 May 2003, http://www.tectite.com/
	 * Purpose:
	 *        Try an AUTH PLAIN authentication method.
	 */
	Function TryAuthPlain($s_data)
	{
		return ($this->PutLine("AUTH PLAIN ".base64_encode($s_data)) &&
		($this->VerifyResultLines("235",$responses) > 0));
	}

	/*
	 * Method:                TryAllAuthPlain
	 * Parameters:        void
	 * Returns:                int                1 on success, 0 on failure
	 * Author:                Russell Robinson, 25 May 2003, http://www.tectite.com/
	 * Purpose:
	 *        Try various AUTH PLAIN authentication methods.
	 */
	Function TryAllAuthPlain()
	{
		//
		// this one is defined by sendmail here:
		// according to: http://www.sendmail.org/~ca/email/authrealms.html#authpwcheck_method
		//
		$s_data = $this->user.chr(0).$this->user.(strlen($this->realm) ? "@".$this->realm : "").chr(0).$this->password;
		if ($this->TryAuthPlain($s_data))
		return (1);

		//
		// Also according to the above document, some sendmails won't accept
		// the realm, so try again without it
		//
		$s_data = $this->user.chr(0).$this->user.chr(0).$this->password;
		if ($this->TryAuthPlain($s_data))
		return (1);

		//
		// I've seen an EXIM configuration like this:
		//                user^password^unused
		// though: http://exim.work.de/exim-html-3.20/doc/html/spec_36.html
		// specifies
		//                ^user^password
		// we'll try both
		//
		$s_data = $this->user.chr(0).$this->password.chr(0);
		if ($this->TryAuthPlain($s_data))
		return (1);
		$s_data = chr(0).$this->user.chr(0).$this->password;
		if ($this->TryAuthPlain($s_data))
		return (1);

		return (0);
	}
	/**
	 * Enter description here...
	 *
	 * @param unknown_type $domain
	 * @param unknown_type $port
	 * @param unknown_type $resolve_message
	 * @return unknown
	 */
	Function ConnectToHost($domain, $port, $resolve_message)
	{
		if(preg_match('/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/',$domain))
		$ip=$domain;
		else
		{
			if($this->debug)
			$this->OutputDebug($resolve_message);
			if(!strcmp($ip=@gethostbyname($domain),$domain))
			return("could not resolve host \"".$domain."\"");
		}
		if(strlen($this->exclude_address)
		&& !strcmp(@gethostbyname($this->exclude_address),$ip))
		return("domain \"".$domain."\" resolved to an address excluded to be valid");
		if($this->debug)
		$this->OutputDebug("Connecting to host address \"".$ip."\"...");
		if(($this->connection=($this->timeout ? @fsockopen($ip,$port,$errno,$error,$this->timeout) : @fsockopen($ip,$port))))
		return("");
		$error=($this->timeout ? strval($error) : "??");
		switch($error)
		{
			case "-3":
				return("-3 socket could not be created");
			case "-4":
				return("-4 dns lookup on hostname \"".$domain."\" failed");
			case "-5":
				return("-5 connection refused or timed out");
			case "-6":
				return("-6 fdopen() call failed");
			case "-7":
				return("-7 setvbuf() call failed");
		}
		return("could not connect to the host \"".$domain."\": ".$error);
	}


	/**
	 * Enter description here...
	 *
	 * @param unknown_type $domain
	 * @return unknown
	 */
	Function Connect($domain="")
	{
		if(strcmp($this->state,"Disconnected"))
		{
			$this->error="connection is already established";
			return(0);
		}
		$this->error=$error="";
		$this->esmtp_host="";
		$this->esmtp_extensions=array();
		$hosts=array();
		if($this->direct_delivery)
		{
			if(strlen($domain)==0)
			return(1);
			$hosts=$weights=$mxhosts=array();
			$getmxrr=$this->getmxrr;
			if(function_exists($getmxrr)
			&& $getmxrr($domain,$hosts,$weights))
			{
				for($host=0;$host<count($hosts);$host++)
				$mxhosts[$weights[$host]]=$hosts[$host];
				KSort($mxhosts);
				for(Reset($mxhosts),$host=0;$host<count($mxhosts);Next($mxhosts),$host++)
				$hosts[$host]=$mxhosts[Key($mxhosts)];
			}
			else
			{
				if(strcmp(@gethostbyname($domain),$domain)!=0)
				$hosts[]=$domain;
			}
		}
		else
		{
			if(strlen($this->host_name))
			$hosts[]=$this->host_name;
			if(strlen($this->pop3_auth_host))
			{
				$user=$this->user;
				if(strlen($user)==0)
				{
					$this->error="it was not specified the POP3 authentication user";
					return(0);
				}
				$password=$this->password;
				if(strlen($password)==0)
				{
					$this->error="it was not specified the POP3 authentication password";
					return(0);
				}
				$domain=$this->pop3_auth_host;
				$this->error=$this->ConnectToHost($domain, $this->pop3_auth_port, "Resolving POP3 authentication host \"".$domain."\":".$this->pop3_auth_port."...");
				if(strlen($this->error))
				return(0);
				if(strlen($response=$this->GetLine())==0)
				return(0);
				if(strcmp($this->Tokenize($response," "),"+OK"))
				{
					$this->error="POP3 authentication server greeting was not found";
					return(0);
				}
				if(!$this->PutLine("USER ".$this->user)
				|| strlen($response=$this->GetLine())==0)
				return(0);
				if(strcmp($this->Tokenize($response," "),"+OK"))
				{
					$this->error="POP3 authentication user was not accepted: ".$this->Tokenize("\r\n");
					return(0);
				}
				if(!$this->PutLine("PASS ".$password)
				|| strlen($response=$this->GetLine())==0)
				return(0);
				if(strcmp($this->Tokenize($response," "),"+OK"))
				{
					$this->error="POP3 authentication password was not accepted: ".$this->Tokenize("\r\n");
					return(0);
				}
				fclose($this->connection);
				$this->connection=0;
			}
		}
		if(count($hosts)==0)
		{
			$this->error="Could not determine the SMTP to connect";
			return(0);
		}
		for($host=0, $error="not connected";strlen($error) && $host<count($hosts);$host++)
		{
			$domain=$hosts[$host];
			$error=$this->ConnectToHost($domain, $this->host_port, "Resolving SMTP server domain \"$domain\":". $this->host_port."...");
		}
		if(strlen($error))
		{
			$this->error=$error;
			return(0);
		}
		$timeout=($this->data_timeout ? $this->data_timeout : $this->timeout);
		if($timeout
		&& function_exists("socket_set_timeout"))
		socket_set_timeout($this->connection,$timeout,0);
		if($this->debug)
		$this->OutputDebug("Connected to SMTP server \"".$domain."\".");
		if(!strcmp($localhost=$this->localhost,"")
		&& !strcmp($localhost=getenv("SERVER_NAME"),"")
		&& !strcmp($localhost=getenv("HOST"),""))
		$localhost="localhost";
		$success=0;
		if($this->VerifyResultLines("220",$responses)>0)
		{
			$fallback=1;
			if($this->esmtp
			|| strlen($this->user))
			{
				if($this->PutLine("EHLO $localhost"))
				{
					if(($success_code=$this->VerifyResultLines("250",$responses))>0)
					{
						$this->esmtp_host=$this->Tokenize($responses[0]," ");
						for($response=1;$response<count($responses);$response++)
						{
							$extension=strtoupper($this->Tokenize($responses[$response]," "));
							$this->esmtp_extensions[$extension]=$this->Tokenize("");
						}
						$success=1;
						$fallback=0;
					}
					else
					{
						if($success_code==0)
						{
							$code=$this->Tokenize($this->error," -");
							switch($code)
							{
								case "421":
									$fallback=0;
									break;
							}
						}
					}
				}
				else
				$fallback=0;
			}
			if($fallback)
			{
				if($this->PutLine("HELO $localhost")
				&& $this->VerifyResultLines("250",$responses)>0)
				$success=1;
			}
			if($success
			&& strlen($this->user)
			&& strlen($this->pop3_auth_host)==0)
			{
				if(!IsSet($this->esmtp_extensions["AUTH"]))
				{
					$this->error="server does not require authentication";
					$success=0;
				}
				else
				{
					for($authentication=$this->Tokenize($this->esmtp_extensions["AUTH"]," ");strlen($authentication);$authentication=$this->Tokenize($remaining_authentication_types," "))
					{
						$remaining_authentication_types=$this->Tokenize("");
						switch($authentication)
						{
							case "PLAIN":
								$success=$this->TryAllAuthPlain();
								break;
							case "LOGIN":
								$success=($this->PutLine("AUTH LOGIN")
								&& $this->VerifyResultLines("334",$responses)
								&& $this->PutLine(base64_encode($this->user.(strlen($this->realm) ? "@".$this->realm : "")))
								&& $this->VerifyResultLines("334",$responses)
								&& $this->PutLine(base64_encode($this->password))
								&& $this->VerifyResultLines("235",$responses));
								break;
						}
						if($success)
						break;
					}
					if($success
					&& strlen($authentication)==0)
					{
						$this->error="the server does not require a supported authentication method";
						$success=0;
					}
				}
			}
		}
		if($success)
		{
			$this->state="Connected";
			$this->connected_domain=$domain;
		}
		else
		{
			fclose($this->connection);
			$this->connection=0;
		}
		return($success);
	}

	Function MailFrom($sender)
	{
		if($this->direct_delivery)
		{
			switch($this->state)
			{
				case "Disconnected":
					$this->direct_sender=$sender;
					return(1);
				case "Connected":
					$sender=$this->direct_sender;
					break;
				default:
					$this->error="direct delivery connection is already established and sender is already set";
					return(0);
			}
		}
		else
		{
			if(strcmp($this->state,"Connected"))
			{
				$this->error="connection is not in the initial state";
				return(0);
			}
		}
		$this->error="";
		if(!$this->PutLine("MAIL FROM:<$sender>"))
		return(0);
		if(!IsSet($this->esmtp_extensions["PIPELINING"])
		&& $this->VerifyResultLines("250",$responses)<=0)
		return(0);
		$this->state="SenderSet";
		if(IsSet($this->esmtp_extensions["PIPELINING"]))
		$this->pending_sender=1;
		$this->pending_recipients=0;
		return(1);
	}

	Function SetRecipient($recipient)
	{
		if($this->direct_delivery)
		{
			if(GetType($at=strrpos($recipient,"@"))!="integer")
			return("it was not specified a valid direct recipient");
			$domain=substr($recipient,$at+1);
			switch($this->state)
			{
				case "Disconnected":
					if(!$this->Connect($domain))
					return(0);
					if(!$this->MailFrom(""))
					{
						$error=$this->error;
						$this->Disconnect();
						$this->error=$error;
						return(0);
					}
					break;
				case "SenderSet":
				case "RecipientSet":
					if(strcmp($this->connected_domain,$domain))
					{
						$this->error="it is not possible to deliver directly to recipients of different domains";
						return(0);
					}
					break;
				default:
					$this->error="connection is already established and the recipient is already set";
					return(0);
			}
		}
		else
		{
			switch($this->state)
			{
				case "SenderSet":
				case "RecipientSet":
					break;
				default:
					$this->error="connection is not in the recipient setting state";
					return(0);
			}
		}
		$this->error="";
		if(!$this->PutLine("RCPT TO: <$recipient>"))
		return(0);
		if(IsSet($this->esmtp_extensions["PIPELINING"]))
		{
			$this->pending_recipients++;
			if($this->pending_recipients>=$this->maximum_piped_recipients)
			{
				if(!$this->FlushRecipients())
				return(0);
			}
		}
		else
		{
			if($this->VerifyResultLines(array("250","251"),$responses)<=0)
			return(0);
		}
		$this->state="RecipientSet";
		return(1);
	}

	Function StartData()
	{
		if(strcmp($this->state,"RecipientSet"))
		{
			$this->error="connection is not in the start sending data state";
			return(0);
		}
		$this->error="";
		if(!$this->PutLine("DATA"))
		return(0);
		if($this->pending_recipients)
		{
			if(!$this->FlushRecipients())
			return(0);
		}
		if($this->VerifyResultLines("354",$responses)<=0)
		return(0);
		$this->state="SendingData";
		return(1);
	}

	Function PrepareData(&$data,&$output,$preg=1)
	{
		if($preg
		&& function_exists("preg_replace"))
		$output=preg_replace(array("/\n\n|\r\r/","/(^|[^\r])\n/","/\r([^\n]|\$)/D","/(^|\n)\\./"),array("\r\n\r\n","\\1\r\n","\r\n\\1","\\1.."),$data);
		else
		$output=preg_replace("/(^|\n)\\.","\\1../",preg_replace("/\r([^\n]|\$)","\r\n\\1/",preg_replace("/(^|[^\r])\n","\\1\r\n/",preg_replace("/\n\n|\r\r/","\r\n\r\n",$data))));

	}

	Function SendData($data)
	{
		if(strcmp($this->state,"SendingData"))
		{
			$this->error="connection is not in the sending data state";
			return(0);
		}
		$this->error="";
		return($this->PutData($data));
	}

	Function EndSendingData()
	{
		if(strcmp($this->state,"SendingData"))
		{
			$this->error="connection is not in the sending data state";
			return(0);
		}
		$this->error="";
		if(!$this->PutLine("\r\n.")
		|| $this->VerifyResultLines("250",$responses)<=0)
		return(0);
		$this->state="Connected";
		return(1);
	}

	Function ResetConnection()
	{
		switch($this->state)
		{
			case "Connected":
				return(1);
			case "SendingData":
				$this->error="can not reset the connection while sending data";
				return(0);
			case "Disconnected":
				$this->error="can not reset the connection before it is established";
				return(0);
		}
		$this->error="";
		if(!$this->PutLine("RSET")
		|| $this->VerifyResultLines("250",$responses)<=0)
		return(0);
		$this->state="Connected";
		return(1);
	}

	Function Disconnect($quit=1)
	{
		if(!strcmp($this->state,"Disconnected"))
		{
			$this->error="it was not previously established a SMTP connection";
			return(0);
		}
		$this->error="";
		if(!strcmp($this->state,"Connected")
		&& $quit
		&& (!$this->PutLine("QUIT")
		|| $this->VerifyResultLines("221",$responses)<=0))
		return(0);
		fclose($this->connection);
		$this->connection=0;
		$this->state="Disconnected";
		if($this->debug)
		$this->OutputDebug("Disconnected.");
		return(1);
	}
	/**
	 * Enter description here...
	 *
	 * @param unknown_type $sender
	 * @param unknown_type $recipients
	 * @param unknown_type $headers
	 * @param unknown_type $body
	 */
	Function SendMessage($sender,$recipients,$headers,$body){
		if(($success=$this->Connect()))
		{
			if(($success=$this->MailFrom($sender)))
			{
				for($recipient=0;$recipient<count($recipients);$recipient++)
				{
					if(!($success=$this->SetRecipient($recipients[$recipient])))
					break;
				}
				if($success
				&& ($success=$this->StartData()))
				{
					for($header_data="",$header=0;$header<count($headers);$header++)
					$header_data.=$headers[$header];

					if(($success=$this->SendData($header_data)))
					{
						$this->PrepareData($body,$body_data);
						$success=$this->SendData($body_data);
					}
					if($success)
					$success=$this->EndSendingData();
				}
			}
			$error=$this->error;
			$disconnect_success=$this->Disconnect($success);
			if($success)
			$success=$disconnect_success;
			else
			$this->error=$error;
		}
		return($success);
	}
	/**
	 * Enter description here...
	 *
	 * @param unknown_type $from
	 * @param unknown_type $namefrom
	 * @param String $to Email To
	 * @param unknown_type $subject
	 * @param unknown_type $msg
	 * @param unknown_type $html
	 * @return unknown
	 */
	function sendemail($from, $namefrom, $to, $subject, $msg, $html=false){

		$msg_original=$msg;

		if (!is_array($to)) {
			if($this->debug)
			$this->OutputDebug("TO is not an array.");
			return false;
		}
		foreach($to as $recipient) {
			if($this->debug)
			$this->OutputDebug("For each address to send...");
			$nameto=$recipient["name"];
			$addrto=$recipient["email"];
			if (array_key_exists("msg",$recipient)) $msg_original = $recipient["msg"];
			if (array_key_exists("id_account",$recipient)) $msg=str_replace("ID_ACCOUNT",$recipient["id_account"], $msg_original);

			if ($this->type==0) {
				$subject_tmp="Subject: $subject\r\n";
				$to = "To: \"".$addrto."\" <".$addrto.">\r\n";
			} else {
				$subject_tmp="";
				$to="";										
			}

			if ($html) $type="html";else $type="plain";
				
			$headers=array("MIME-Version: 1.0\r\n", "Content-type: text/$type; charset="._CHARSET."\r\n","From: \"$namefrom\" <$from>\r\n",$to,$subject_tmp, "Date: ".strftime("%a, %d %b %Y %H:%M:%S %Z")."\r\n");
           
			//if smtp
			if ($this->type==0) {
				if($this->debug) $this->OutputDebug("Sent using smtp server...");
				if (!$this->SendMessage($from,array($addrto),$headers,$msg))
				if($this->debug) $this->OutputDebug($this->error);
			}
			//if php mail function
			if ($this->type==1) {
				if (!$html) {
					$headers[5]="";
					$headers[1]="";
					$headers[4]="";
				}
				if($this->debug)
				$this->OutputDebug("Sent using php mail function...");
				mail($addrto,$subject,$msg,$headers[0]."".$headers[1]."".$headers[2]."".$headers[3]."".$headers[4]."".$headers[5]);
			}
		}
	}
	/**
	 * Enter description here...
	 *
	 * @param unknown_type $email
	 * @return unknown
	 */
	function _is_valid_email ($email = "")
	{ return preg_match('/^[.\w-]+@([\w-]+\.)+[a-zA-Z]{2,6}$/', $email); }
	/**
	 * Enter description here...
	 *
	 * @param unknown_type $email
	 * @return unknown
	 */
	function check_mail ($email = ""){

		if (!$this->_is_valid_email ($email))
		{ return false; }

		$host = substr (strstr ($email, '@'), 1);

		//if ($this->_check_domain_rules ($host))
		//{ return false; }

		$host .= ".";

		if (getmxrr ($host, $mxhosts[0],  $mxhosts[1]) == true)
		{ array_multisort ($mxhosts[1],  $mxhosts[0]); }
		else
		{
			$mxhosts[0] = $host;
			$mxhosts[1] = 10;
		}
		if ($this->debug) { $this->OutputDebug ($mxhosts); }

		$port = 25;
		$localhost = $_SERVER['HTTP_HOST'];
		$sender = 'info@' . $localhost;

		$result = false;
		$id = 0;
		while (!$result && $id < count ($mxhosts[0]))
		{
			if (function_exists ("fsockopen"))
			{
				if ($this->debug) { $this->OutputDebug ($id . " " . $mxhosts[0][$id]); }
				if ($connection = fsockopen ($mxhosts[0][$id], $port, $errno, $error, $this->timeout))
				{
					fputs ($connection,"HELO $localhost\r\n"); // 250
					$data = fgets ($connection,1024);
					$response = substr ($data,0,1);
					if ($this->debug) { $this->OutputDebug ($data); }

					if ($response == '2') // 200, 250 etc.
					{
						fputs ($connection,"MAIL FROM:<$sender>\r\n");
						$data = fgets($connection,1024);
						$response = substr ($data,0,1);
						if ($this->debug) { $this->OutputDebug ($data); }

						if ($response == '2') // 200, 250 etc.
						{
							fputs ($connection,"RCPT TO:<$email>\r\n");
							$data = fgets($connection,1024);
							$response = substr ($data,0,1);
							if ($this->debug) { $this->OutputDebug ($data); }

							if ($response == '2') // 200, 250 etc.
							{
								fputs ($connection,"data\r\n");
								$data = fgets($connection,1024);
								$response = substr ($data,0,1);
								if ($this->debug) { $this->OutputDebug ($data); }

								if ($response == '2') // 200, 250 etc.
								{ $result = true; }
							}
						}
					}

					fputs ($connection,"QUIT\r\n");
					fclose ($connection);
					if ($result) { return true; }
				}
			}
			else
			{ break; }
			$id++;
		}
		return false;
	}
	/**
	 * Enter description here...
	 *
	 * @param unknown_type $from
	 * @param unknown_type $to
	 * @param unknown_type $subject
	 * @param unknown_type $message
	 * @param unknown_type $cc
	 * @param unknown_type $bcc
	 * @return unknown
	 */
	private function UTF8_mail($from,$to,$subject,$message,$cc="",$bcc=""){

		$from = explode("<",$from );

		$headers = "From: =?UTF-8?B?".base64_encode($from[0])."?= <". $from[1] . "\r\n";

		$to = explode("<",$to );
		$to = "=?UTF-8?B?".base64_encode($to[0])."?= <". $to[1] ;

		$subject="=?UTF-8?B?".base64_encode($subject)."?=\n";

		if($cc!=""){
			$cc = explode("<",$cc );
			$headers .= "Cc: =?UTF-8?B?".base64_encode($cc[0])."?= <".$cc[1] . "\r\n";
		}

		if($bcc!=""){
			$bcc = explode("<",$bcc );
			$headers .= "Bcc: =?UTF-8?B?".base64_encode($bcc[0])."?= <". $bcc[1] . "\r\n";
		}

		$headers .=
			"Content-Type: text/plain; "
		. "charset=UTF-8; format=flowed\n"
		. "MIME-Version: 1.0\n"
		. "Content-Transfer-Encoding: 8bit\n"
		. "X-Mailer: PHP\n";

		return mail($to, $subject, $message, $headers);
	}

	//********************* CLASS END *******************************************************

};

?>