⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 class_smtp.php

📁 webmail系统 php + mysql
💻 PHP
📖 第 1 页 / 共 2 页
字号:
<?php

class phpmailer {
	var $Priority         = 3;
	var $CharSet          = "iso-8859-1";
	var $ContentType      = "text/plain";
	var $Encoding         = "8bit";
	var $From             = "root@localhost";
	var $FromName         = "root";
	var $Subject          = "";
	var $Body             = "";
	var $WordWrap         = true;
	var $MailerDebug      = false;
	var $UseMSMailHeaders = true;

	// SMTP

	var $Host        = "localhost";
	var $Port        = 25;
	var $Helo        = "";
	var $Timeout     = 10; // Socket timeout in sec.
	var $SMTPDebug   = false;

	
	/////////////////////////////////////////////////
	// PRIVATE VARIABLES
	/////////////////////////////////////////////////
	var $version        = "";
	var $to             = array();
	var $cc             = array();
	var $bcc            = array();
	var $ReplyTo        = array();
	var $attachment     = array();
	var $CustomHeader   = array();	
	var $boundary       = false;
	var $ErrorAlerts    = Array();
	var $blUseAuthLogin = false;
	var $AuthUser       = "";
	var $AuthPass       = "";

	function UseAuthLogin($user,$pass) {
		$this->blUseAuthLogin = true;
		$this->AuthUser = $user;
		$this->AuthPass = $pass;
	}
	
	/////////////////////////////////////////////////
	// VARIABLE METHODS
	/////////////////////////////////////////////////
	function IsHTML($bool) {
		if($bool == true)
			$this->ContentType = "text/html";
		else
			$this->ContentType = "text/plain";
	}

	/////////////////////////////////////////////////
	// LOAD VARIABLES
	/////////////////////////////////////////////////

	function Start() {
		global $appname,$appversion;
		$this->Version = $appname." ".$appversion;
		$this->Helo = ereg_replace("[^A-Za-z0-9]","",$appname);
	}


	/////////////////////////////////////////////////
	// RECIPIENT METHODS
	/////////////////////////////////////////////////	

	
	function AddAddress($address, $name = "") {
		$cur = count($this->to);
		$this->to[$cur][0] = trim($address);
		$this->to[$cur][1] = $name;
	}

	function AddCC($address, $name = "") {
		$cur = count($this->cc);
		$this->cc[$cur][0] = trim($address);
		$this->cc[$cur][1] = $name;
	}

	function AddBCC($address, $name = "") {
		$cur = count($this->bcc);
		$this->bcc[$cur][0] = trim($address);
		$this->bcc[$cur][1] = $name;
	}

	function AddReplyTo($address, $name = "") {
		$cur = count($this->ReplyTo);
		$this->ReplyTo[$cur][0] = trim($address);
		$this->ReplyTo[$cur][1] = $name;
	}


	/////////////////////////////////////////////////
	// MAIL SENDING METHODS
	/////////////////////////////////////////////////

	/**
	 * Send method creates message and assigns Mailer.  Returns bool.
	 * @public
	 * @returns bool
	 */
	function Send() {
		if(count($this->to)+count($this->cc)+count($this->bcc) == 0) {
			$this->error_handler("You must provide at least one recipient email address");
			return false;
		}
		$header = $this->create_header();

		if(($body = $this->create_body()) === false)
		   return false;

		if($this->smtp_send($header, $body) === false)
		   return false;
		return sprintf("%s%s", $header, $body);
	}

	function smtp_send($header, $body) {

		$smtp = new SMTP;
		$smtp->do_debug = $this->SMTPDebug;
		$hosts = explode(";", $this->Host);
		$index = 0;
		$connection = false;
		
		while($index < count($hosts) && $connection == false) {
			if($smtp->Connect($hosts[$index], $this->Port, $this->Timeout))
				$connection = true;
			$index++;
		}

		if(!$connection) {
			$this->error_handler("SMTP Error: could not connect to SMTP host server(s)");
			return false;
		}

		if($this->blUseAuthLogin) {
			if(!$smtp->AuthHello($this->Helo,$this->AuthUser,$this->AuthPass)) {
			   $this->error_handler("SMTP Error: Inv醠id username/password");
			   return false;
			}
		} else
			$smtp->Hello($this->Helo);

		$smtp->MailFrom(sprintf("<%s>", $this->From));
		for($i = 0; $i < count($this->to); $i++)
			$smtp->Recipient(sprintf("<%s>", $this->to[$i][0]));
		for($i = 0; $i < count($this->cc); $i++)
			$smtp->Recipient(sprintf("<%s>", $this->cc[$i][0]));
		for($i = 0; $i < count($this->bcc); $i++)
			$smtp->Recipient(sprintf("<%s>", $this->bcc[$i][0]));
		if(!$smtp->Data(sprintf("%s%s", $header, $body))) {
		   $this->error_handler("SMTP Error: Data not accepted");
		   return false;
		}
		$smtp->Quit();
	}

	/////////////////////////////////////////////////
	// MESSAGE CREATION METHODS
	/////////////////////////////////////////////////

	function addr_append($type, $addr) {
		$addr_str = "";
		$addr_str .= sprintf("%s: %s <%s>", $type, $addr[0][1], $addr[0][0]);

		if(count($addr) > 1) {
			for($i = 1; $i < count($addr); $i++) {
				$addr_str .= sprintf(", %s <%s>", $addr[$i][1], $addr[$i][0]);
			}
			$addr_str .= "\r\n";
		} else
			$addr_str .= "\r\n";

		return($addr_str);
	}

	function wordwrap($message, $length) {
		$line = explode("\n", $message);
		$message = "";
		for ($i=0 ;$i < count($line); $i++) 
		{
			$line_part = explode(" ", trim($line[$i]));
			$buf = "";
			for ($e = 0; $e<count($line_part); $e++) 
			{
				$buf_o = $buf;
				if ($e == 0)
					$buf .= $line_part[$e];
				else 
					$buf .= " " . $line_part[$e];
				if (strlen($buf) > $length and $buf_o != "")
				{
					$message .= $buf_o . "\n";
					$buf = $line_part[$e];
				}
			}
			$message .= $buf . "\n";
		}
		
		return ($message);
	}

	function create_header() {
		$this->Start();
		$header = array();
		$header[] = sprintf("Date: %s\r\n", date("D, j M Y G:i:s"));

		$header[] = sprintf("From: %s <%s>\r\n", $this->FromName, trim($this->From));
		if(count($this->to) > 0)
			$header[] = $this->addr_append("To", $this->to);
		if(count($this->cc) > 0)
			$header[] = $this->addr_append("Cc", $this->cc);
		if(count($this->bcc) > 0)
			$header[] = $this->addr_append("Bcc", $this->bcc);
		if(count($this->ReplyTo) > 0)
			$header[] = $this->addr_append("Reply-to", $this->ReplyTo);
		$header[] = sprintf("Subject: %s\r\n", trim($this->Subject));
		$header[] = sprintf("X-Priority: %d\r\n", $this->Priority);
		$header[] = sprintf("X-Mailer: %s\r\n", $this->Version);
		$header[] = sprintf("Content-Transfer-Encoding: %s\r\n", $this->Encoding);
		$header[] = sprintf("Return-Path: %s\r\n", trim($this->From));
		
		// Add custom headers
		for($index = 0; $index < count($this->CustomHeader); $index++)
		   $header[] = sprintf("%s\r\n", $this->CustomHeader[$index]);

		if($this->UseMSMailHeaders)
		   $header[] = $this->UseMSMailHeaders();

		// Add all attachments
		if(count($this->attachment) > 0)
		{
			$header[] = sprintf("Content-Type: multipart/mixed; charset=\"%s\";\r\n", $this->CharSet);
			$header[] = sprintf(" boundary=\"--=%s\"\r\n", $this->boundary);
		}
		else
			$header[] = sprintf("Content-Type: %s; charset=\"%s\";\r\n", $this->ContentType, $this->CharSet);
		
		$header[] = "MIME-Version: 1.0\r\n";
		
		return(join("", $header)."\r\n");
	}

	function create_body() {
		if($this->WordWrap)
			$this->Body = $this->wordwrap($this->Body, $this->WordWrap);
		if(count($this->attachment) > 0) {
			if(!$body = $this->attach_all())
			   return false;
		}
		else
			$body = $this->Body;
		
		return(trim($body));		
	}
	
	
	/////////////////////////////////////////////////
	// ATTACHMENT METHODS
	/////////////////////////////////////////////////

	function AddAttachment($path, $name = "", $type= "application/octet-stream") {
		if(!@is_file($path)) {
			$this->error_handler(sprintf("Could not find %s file on filesystem", $path));
			return false;
		}
		$filename = basename($path);
		if($name == "")
		   $name = $filename;
		
		$this->boundary = "_b" . md5(uniqid(time()));

		$cur = count($this->attachment);
		$this->attachment[$cur][0] = $path;
		$this->attachment[$cur][1] = $filename;
		$this->attachment[$cur][2] = $name;
		$this->attachment[$cur][3] = $type;

		return true;
	}


	function attach_all() {

		$mime = array();
		$mime[] = sprintf("----=%s\n", $this->boundary);
		$mime[] = sprintf("Content-Type: %s\n", $this->ContentType);
		$mime[] = "Content-Transfer-Encoding: 8bit\n\n";
		$mime[] = sprintf("%s\n", $this->Body);
		
		for($i = 0; $i < count($this->attachment); $i++) {
			$path = $this->attachment[$i][0];
			$filename = $this->attachment[$i][1];
			$name = $this->attachment[$i][2];
			$type = $this->attachment[$i][3];
			$mime[] = sprintf("----=%s\n", $this->boundary);
			$mime[] = "Content-Type: $type;\n";
			$mime[] = sprintf("name=\"%s\"\n", $name);
			$mime[] = "Content-Transfer-Encoding: base64\n";
			$mime[] = sprintf("Content-Disposition: attachment; filename=\"%s\"\n\n", $name);
			if(!$mime[] = sprintf("%s\n\n", $this->encode_file($path)))
			   return false;
		}
		$mime[] = sprintf("\n----=%s--\n", $this->boundary);
		
		return(join("", $mime));
	}

	function encode_file ($path) {
		if(!@$fd = fopen($path, "r"))
		{
			$this->error_handler("File Error: Could not open file $path");
			return false;
		}
		$file = fread($fd, filesize($path));
		
		// chunk_split is found in PHP >= 3.0.6
		$encoded = chunk_split(base64_encode($file));
		fclose($fd);
		
		return($encoded);
	}
	
	/////////////////////////////////////////////////
	// MESSAGE RESET METHODS
	/////////////////////////////////////////////////

	function ClearAddresses() {
	   $this->to = array();
	}

	function ClearCCs() {
	   $this->cc = array();
	}

	function ClearBCCs() {
	   $this->bcc = array();
	}

	function ClearReplyTos() {
	   $this->ReplyTo = array();
	}

	function ClearAllRecipients() {
	   $this->to = array();
	   $this->cc = array();
	   $this->bcc = array();
	}

	function ClearAttachments() {
	   $this->attachment = array();
	}

	function ClearCustomHeaders() {
	   $this->CustomHeader = array();
	}

	/////////////////////////////////////////////////
	// MISCELLANEOUS METHODS
	/////////////////////////////////////////////////

	function error_handler($msg) {
		$this->ErrorAlerts[] = $msg;
		if($this->MailerDebug == true) {
			print("<h3>Mailer Error</h3>");
			print("Description:<br>");
			printf("<font color=\"FF0000\">%s</font>", $msg);
		}
	}

	function AddCustomHeader($custom_header) {
	   $this->CustomHeader[] = $custom_header;
	}

	function UseMSMailHeaders() {
	   $MSHeader = "";
	   if($this->Priority == 1)
	      $MSPriority = "High";
	   elseif($this->Priority == 5)
	      $MSPriority = "Low";
	   else
	      $MSPriority = "Medium";
	      
	   $MSHeader .= sprintf("X-MSMail-Priority: %s\n", $MSPriority);
	   $MSHeader .= sprintf("Importance: %s\n", $MSPriority);
	   
	   return($MSHeader);
	}


}
// End of class

class SMTP {
    var $SMTP_PORT = 25; # the default SMTP PORT
    var $CRLF = "\r\n";  # CRLF pair

    var $smtp_conn;      # the socket to the server
    var $error;          # error if any on the last call
    var $helo_rply;      # the reply the server sent to us for HELO

    var $do_debug;       # the level of debug to perform

    /*
     * SMTP()
     *
     * Initialize the class so that the data is in a known state.
     */
    function SMTP() {
        $this->smtp_conn = 0;
        $this->error = null;
        $this->helo_rply = null;
        $this->do_debug = 0;
    }

    /************************************************************
     *                    CONNECTION FUNCTIONS                  *
     ***********************************************************/


    /*
     * Connected()
     *
     * Returns true if connected to a server otherwise false
     */
    function Connected() {
        if(!empty($this->smtp_conn)) {
            $sock_status = socket_get_status($this->smtp_conn);
            if($sock_status["eof"]) {
                # hmm this is an odd situation... the socket is
                # valid but we aren't connected anymore
                if($this->do_debug >= 1) {
                    echo "SMTP -> NOTICE:" . $this->CRLF .
                         "EOF caught while checking if connected";
                }
                $this->Close();
                return false;
            }
            return true; # everything looks good
        } 
        return false;
    }


    /*
     * Connect($host, $port=0, $tval=30)
     *
     * Connect to the server specified on the port specified.
     * If the port is not specified use the default SMTP_PORT.
     * If tval is specified then a connection will try and be
     * established with the server for that number of seconds.
     * If tval is not specified the default is 30 seconds to
     * try on the connection.
     *
     * SMTP CODE SUCCESS: 220
     * SMTP CODE FAILURE: 421
     */
    function Connect($host,$port=0,$tval=30) {
        # set the error val to null so there is no confusion
        $this->error = null;

        # make sure we are __not__ connected
        if($this->connected()) {
            # ok we are connected! what should we do?
            # for now we will just give an error saying we
            # are already connected
            $this->error =
                array("error" => "Already connected to a server");
            return false;
        }

        if(empty($port)) {
            $port = $this->SMTP_PORT;
        }

        #connect to the smtp server
        $this->smtp_conn = fsockopen($host,    # the host of the server

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -