<?php
 /**
 *      [XCECP] (C) Colorful Network Inc.
 *      This is NOT a freeware, use is subject to license terms
 */
if(!defined("IN_QKWEB")){exit("Access Denied");}
class MailTemplate{

    var $from;

	var $reply;

	var $mailtype;

	var $body;

	var $smtp;
	
	var $initbody;

	var $SmtpServer;

	var $SmtpUser;

	var $SmtpPW;

	var $SmtpSender;

	var $SmtpPort = 25;
	var $msg = '';
	var $fromName = '';

	function MailTemplate($initParam){
		
		if(preg_match("/^(file=){1,1}/",$initParam)){
	       
		   $filename=preg_replace("/^(file=){1,1}/","",$initParam);
		   
		   $this->body=@implode("",file($filename));
		   if(!$this->body){
				$this->msg = '邮件模板文件不存在';
				return false;
		   }
		   //exit($filename);
		
		}else{
		   
		   $this->body=$initParam;
		}
		$this->initbody = $this->body;
		
		if(preg_match("/<html>/",$this->body) || preg_match("/<!DOCTYPE html/",$this->body))$this->mailtype = "HTML";
		
		else $this->mailtype = "TXT";
	}
	
	function reset(){
	    
		$this->body=$this->initbody;
	}

	function var2value($var,$val){
	    
		$this->body=str_replace("$".$var."$",$val,$this->body);
	}

	function var2value_ary($array){
	    
		foreach($array as $var=>$val){
		   
		   $this->var2value($var,$val);
		}
	}

	function setReplyTo($reply){
	    
		$this->reply="Reply-To:$reply";
	}

	function getSmtpInstance(){
		if(!$this->smtp){
			$this->smtp = new smtp($this->SmtpServer,$this->SmtpPort,true,$this->SmtpUser,$this->SmtpPW,$this->SmtpSender);// true 表示要通过SMTP验证才能发邮件
			$this->smtp->debug = false;//是否显示调试信息
		}
	}

	function sendmail($to,$subject,$from){
			
		if($to==''){
			$this->msg = "收件人为空，发送中止";
			return 0;
		}
		if($from==''){
			$this->msg = "发件人为空，发送中止";
			return 0;
		}
		$this->getSmtpInstance();
		//exit($this->SmtpSender);
		$this->smtp->fromName = $this->fromName;
		//$this->smtp->debug = true;
		$sent = $this->smtp->sendmail($to,$from, $subject, $this->body, $this->mailtype);
		if(!$sent){
			saveLog("邮件发送失败： 主体：".$subject." 收件人：".$to." 日志：".$this->smtp->logs);
			if(strpos($this->smtp->logs,"535 Authentication failed")){
				$this->msg = 'SMTP邮件配置错误，登录失败';
			}
		}
		
		return $sent;
	}

}
?>