1. 程式人生 > >PHP 郵件傳送類

PHP 郵件傳送類


mail.php


<?php
/**
* 郵件傳送類
* 支援傳送純文字郵件和HTML格式的郵件,可以多收件人,多抄送,多祕密抄送,帶附件的郵件
* 需要的php擴充套件,sockets和Fileinfo。
* @example
* $mail = new MySendMail();
* $mail->setServer("XXXXX", "[email protected]", "XXXXX"); 設定smtp伺服器
* $mail->setFrom("XXXXX"); 設定發件人
* $mail->setReceiver("XXXXX"); 設定收件人,多個收件人,呼叫多次
* $mail->setCc("XXXX"); 設定抄送,多個抄送,呼叫多次
* $mail->setBcc("XXXXX"); 設定祕密抄送,多個祕密抄送,呼叫多次
* $mail->setMailInfo("test", "<b>test</b>"); 設定郵件主題、內容
* $mail->sendMail(); 傳送
*/
class MySendMail {
  /**
    * @var string 郵件傳輸代理使用者名稱
    * @access private
    */
    private $_userName;

    /**
    * @var string 郵件傳輸代理密碼
    * @access private
    */
    private $_password;

    /**
    * @var string 郵件傳輸代理伺服器地址
    * @access protected
    */
    protected $_sendServer;

    /**
    * @var int 郵件傳輸代理伺服器埠
    * @access protected
    */
    protected $_port=25;

    /**
    * @var string 發件人
    * @access protected
    */
    protected $_from;

    /**
    * @var string 收件人
    * @access protected
    */
    protected $_to;

    /**
    * @var string 抄送
    * @access protected
    */
    protected $_cc;

    /**
    * @var string 祕密抄送
    * @access protected
    */
    protected $_bcc;

    /**
    * @var string 主題
    * @access protected
    */
    protected $_subject;

    /**
    * @var string 郵件正文
    * @access protected
    */
    protected $_body;

    /**
    * @var string 附件
    * @access protected
    */
    protected $_attachment;

    /**
    * @var reource socket資源
    * @access protected
    */
    protected $_socket;

    /**
    * @var string 錯誤資訊
    * @access protected
    */
    protected $_errorMessage;   /**
    * 設定郵件傳輸代理,如果是可以匿名傳送有郵件的伺服器,只需傳遞代理伺服器地址就行
    * @access public
    * @param string $server 代理伺服器的ip或者域名
    * @param string $username 認證賬號
    * @param string $password 認證密碼
    * @param int $port 代理伺服器的埠,smtp預設25號埠
    * @return boolean
    */
    public function setServer($server, $username="", $password="", $port=25) {
        $this->_sendServer = $server;
        $this->_port = $port;
        if(!empty($username)) {
            $this->_userName = base64_encode($username);
        }
        if(!empty($password)) {
            $this->_password = base64_encode($password);
        }
        return true;
    }

    /**
    * 設定發件人
    * @access public
    * @param string $from 發件人地址
    * @return boolean
    */
    public function setFrom($from) {
        $this->_from = $from;
        return true;
    }

    /**
    * 設定收件人,多個收件人,連續呼叫多次.
    * @access public
    * @param string $to 收件人地址
    * @return boolean
    */
    public function setReceiver($to) {
        if(isset($this->_to)) {
            if(is_string($this->_to)) {
                $this->_to = array($this->_to);
                $this->_to[] = $to;
                return true;
            }
            elseif(is_array($this->_to)) {
                $this->_to[] = $to;
                return true;
            }
            else {
                return false;
            }
        }
        else {
            $this->_to = $to;
            return true;
        }
    }

    /**
    * 設定抄送,多個抄送,連續呼叫多次.
    * @access public
    * @param string $cc 抄送地址
    * @return boolean
    */
    public function setCc($cc) {
        if(isset($this->_cc)) {
            if(is_string($this->_cc)) {
                $this->_cc = array($this->_cc);
                $this->_cc[] = $cc;
                return true;
            }
            elseif(is_array($this->_cc)) {
                $this->_cc[] = $cc;
                return true;
            }
            else {
                return false;
            }
        }
        else {
            $this->_cc = $cc;
            return true;
        }
    }

    /**
    * 設定祕密抄送,多個祕密抄送,連續呼叫多次
    * @access public
    * @param string $bcc 祕密抄送地址
    * @return boolean
    */
    public function setBcc($bcc) {
        if(isset($this->_bcc)) {
            if(is_string($this->_bcc)) {
                $this->_bcc = array($this->_bcc);
                $this->_bcc[] = $bcc;
                return true;
            }
            elseif(is_array($this->_bcc)) {
                $this->_bcc[] = $bcc;
                return true;
            }
            else {
                return false;
            }
        }
        else {
            $this->_bcc = $bcc;
            return true;
        }
    }

    /**
    * 設定郵件資訊
    * @access public
    * @param string $body 郵件主題
    * @param string $subject 郵件主體內容,可以是純文字,也可是是HTML文字
    * @param string $attachment 附件,檔案地址
    * @return boolean
    */
    public function setMailInfo($subject, $body, $attachment="") {
        $this->_subject = $subject;
        $this->_body = base64_encode($body);
        if(!empty($attachment)) {
            $this->_attachment = $attachment;
        }
        return true;
    }

    /**
    * 傳送郵件
    * @access public
    * @return boolean
    */
    public function sendMail() {
        $command = $this->getCommand();
        $this->socket();
        
        foreach ($command as $value) {
            if($this->sendCommand($value[0], $value[1])) {
                continue;
            }
            else{
                return false;
            }
        }
        
        //其實這裡也沒必要關閉,smtp命令:QUIT發出之後,伺服器就關閉了連線,本地的socket資源會自動釋放
        $this->close(); 
        echo 'Mail OK!';
        return true;
    }

    /**
    * 返回錯誤資訊
    * @return string
    */
    public function error(){
        if(!isset($this->_errorMessage)) {
            $this->_errorMessage = "";
        }
        return $this->_errorMessage;
    }

    /**
    * 返回mail命令
    * @access protected
    * @return array
    */
    protected function getCommand() {
        $command = array(
                array("HELO sendmail\r\n", 250)
            );
        if(!empty($this->_userName)){
            $command[] = array("AUTH LOGIN\r\n", 334);
            $command[] = array($this->_userName . "\r\n", 334);
            $command[] = array($this->_password . "\r\n", 235);
        }
        $command[] = array("MAIL FROM:<" . $this->_from . ">\r\n", 250);       $separator = "----=_Part_" . md5($this->_from . time()) . uniqid(); //分隔符
        //設定發件人
        $header = "FROM: test<" . $this->_from . ">\r\n";

        //設定收件人
        if(is_array($this->_to)) {
            $count = count($this->_to);
            for($i=0; $i<$count; $i++){
                $command[] = array("RCPT TO: <" . $this->_to[$i] . ">\r\n", 250);
                if($i == 0){
                    $header .= "TO: <" . $this->_to[$i] .">";
                }
                elseif($i + 1 == $count){
                    $header .= ",<" . $this->_to[$i] .">\r\n";
                }
                else{
                    $header .= ",<" . $this->_to[$i] .">";
                }
            }
        }
        else{
            $command[] = array("RCPT TO: <" . $this->_to . ">\r\n", 250);
            $header .= "TO: <" . $this->_to . ">\r\n";
        }

        //設定抄送
        if(isset($this->_cc)) {
            if(is_array($this->_cc)) {
                $count = count($this->_cc);
                for($i=0; $i<$count; $i++){
                    $command[] = array("RCPT TO: <" . $this->_cc[$i] . ">\r\n", 250);
                    if($i == 0){
                    $header .= "CC: <" . $this->_cc[$i] .">";
                    }
                    elseif($i + 1 == $count){
                        $header .= ",<" . $this->_cc[$i] .">\r\n";
                    }
                    else{
                        $header .= ",<" . $this->_cc[$i] .">";
                    }
                }
            }
            else{
                $command[] = array("RCPT TO: <" . $this->_cc . ">\r\n", 250);
                $header .= "CC: <" . $this->_cc . ">\r\n";
            }
        }

        //設定祕密抄送
        if(isset($this->_bcc)) {
            if(is_array($this->_bcc)) {
                $count = count($this->_bcc);
                for($i=0; $i<$count; $i++){
                    $command[] = array("RCPT TO: <" . $this->_bcc[$i] . ">\r\n", 250);
                    if($i == 0){
                    $header .= "BCC: <" . $this->_bcc[$i] .">";
                    }
                    elseif($i + 1 == $count){
                        $header .= ",<" . $this->_bcc[$i] .">\r\n";
                    }
                    else{
                        $header .= ",<" . $this->_bcc[$i] .">";
                    }
                }
            }
            else{
                $command[] = array("RCPT TO: <" . $this->_bcc . ">\r\n", 250);
                $header .= "BCC: <" . $this->_bcc . ">\r\n";
            }
        }

        $header .= "Subject: " . $this->_subject ."\r\n";
        if(isset($this->_attachment)) {
            //含有附件的郵件頭需要宣告成這個
            $header .= "Content-Type: multipart/mixed;\r\n";
        }
        elseif(false){
            //郵件體含有圖片資源的需要宣告成這個
            $header .= "Content-Type: multipart/related;\r\n";
        }
        else{
            //html或者純文字的郵件宣告成這個
            $header .= "Content-Type: multipart/alternative;\r\n";
        }

        //郵件頭分隔符
        $header .= "\t" . 'boundary="' . $separator . '"';
        $header .= "\r\nMIME-Version: 1.0\r\n";
        $header .= "\r\n--" . $separator . "\r\n";
        $header .= "Content-Type:text/html; charset=utf-8\r\n";
        $header .= "Content-Transfer-Encoding: base64\r\n\r\n";
        $header .= $this->_body . "\r\n";
        $header .= "--" . $separator . "\r\n";

        //加入附件
        if(isset($this->_attachment)){
            $header .= "\r\n--" . $separator . "\r\n";
            $header .= "Content-Type: " . $this->getMIMEType() . '; name="' . basename($this->_attachment) . '"' . "\r\n";
            $header .= "Content-Transfer-Encoding: base64\r\n";
            $header .= 'Content-Disposition: attachment; filename="' . basename($this->_attachment) . '"' . "\r\n";
            $header .= "\r\n";
            $header .= $this->readFile();
            $header .= "\r\n--" . $separator . "\r\n";
        }

        $header .= "\r\n.\r\n";     $command[] = array("DATA\r\n", 354);
        $command[] = array($header, 250);
        $command[] = array("QUIT\r\n", 221);
        
        return $command;
    }

    /**
    * 傳送命令
    * @access protected
    * @param string $command 傳送到伺服器的smtp命令
    * @param int $code 期望伺服器返回的響應嗎
    * @return boolean
    */
    protected function sendCommand($command, $code) {
        echo 'Send command:' . $command . ',expected code:' . $code . '<br />';
        //傳送命令給伺服器
        try{
            if(socket_write($this->_socket, $command, strlen($command))){

                //當郵件內容分多次傳送時,沒有$code,伺服器沒有返回
                if(empty($code))  {
                    return true;
                }

                //讀取伺服器返回
                $data = trim(socket_read($this->_socket, 1024));
                echo 'response:' . $data . '<br /><br />';

                if($data) {
                    $pattern = "/^".$code."/";
                    if(preg_match($pattern, $data)) {
                        return true;
                    }
                    else{
                        $this->_errorMessage = "Error:" . $data . "|**| command:";
                        return false;
                    }
                }
                else{
                    $this->_errorMessage = "Error:" . socket_strerror(socket_last_error());
                    return false;
                }
            }
            else{
                $this->_errorMessage = "Error:" . socket_strerror(socket_last_error());
                return false;
            }
        }catch(Exception $e) {
            $this->_errorMessage = "Error:" . $e->getMessage();
        }
    }

    /**
    * 讀取附件檔案內容,返回base64編碼後的檔案內容
    * @access protected
    * @return mixed
    */
    protected function readFile() {
        if(isset($this->_attachment) && file_exists($this->_attachment)) {
            $file = file_get_contents($this->_attachment);
            return base64_encode($file);
        }
        else {
            return false;
        }
    }

    /**
    * 獲取附件MIME型別
    * @access protected
    * @return mixed
    */
    protected function getMIMEType() {
        if(isset($this->_attachment) && file_exists($this->_attachment)) {
            $mime = mime_content_type($this->_attachment);
            if(! preg_match("/gif|jpg|png|jpeg/", $mime)){
                $mime = "application/octet-stream";
            }
            return $mime;
        }
        else {
            return false;
        }
    }

    /**
    * 建立到伺服器的網路連線
    * @access private
    * @return boolean
    */
    private function socket() {
        if(!function_exists("socket_create")) {
            $this->_errorMessage = "Extension sockets must be enabled";
            return false;
        }
        //建立socket資源
        $this->_socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));
        
        if(!$this->_socket) {
            $this->_errorMessage = socket_strerror(socket_last_error());
            return false;
        }

        socket_set_block($this->_socket);//設定阻塞模式

        //連線伺服器
        if(!socket_connect($this->_socket, $this->_sendServer, $this->_port)) {
            $this->_errorMessage = socket_strerror(socket_last_error());
            return false;
        }
        socket_read($this->_socket, 1024);
        
        return true;
    }

    /**
    * 關閉socket
    * @access private
    * @return boolean
    */
    private function close() {
        if(isset($this->_socket) && is_object($this->_socket)) {
            $this->_socket->close();
            return true;
        }
        $this->_errorMessage = "No resource can to be close";
        return false;
    }
}
<?php
/**
* 郵件傳送類
* 僅支援傳送純文字和HTML內容郵件
* 需要的php擴充套件,sockets
* @example
* $mail = new MySendMail();
* $mail->setServer("XXXXX", "
[email protected]
", "XXXXX"); 設定smtp伺服器 * $mail->setFrom("XXXXX"); 設定發件人 * $mail->setReceiver("XXXXX"); 設定收件人 * $mail->setMailInfo("test", "<b>test</b>"); 設定郵件主題、內容 * $mail->sendMail(); 傳送 */ class MySendMail2 { /** * @var string 郵件傳輸代理使用者名稱 * @access private */ private $_userName; /** * @var string 郵件傳輸代理密碼 * @access private */ private $_password; /** * @var string 郵件傳輸代理伺服器地址 * @access private */ private $_sendServer; /** * @var int 郵件傳輸代理伺服器埠 * @access protected */ protected $_port=25; /** * @var string 發件人 * @access protected */ protected $_from; /** * @var string 收件人 * @access protected */ protected $_to; /** * @var string 主題 * @access protected */ protected $_subject; /** * @var string 郵件正文 * @access protected */ protected $_body; /** * @var reource socket資源 * @access protected */ protected $_socket; /** * @var string 錯誤資訊 * @access protected */ protected $_errorMessage; /** * 設定郵件傳輸代理,如果是可以匿名傳送有郵件的伺服器,只需傳遞代理伺服器地址就行 * @access public * @param string $server 代理伺服器的ip或者域名 * @param string $username 認證賬號 * @param string $password 認證密碼 * @param int $port 代理伺服器的埠,smtp預設25號埠 * @return boolean */ public function setServer($server, $username="", $password="", $port=25) { $this->_sendServer = $server; $this->_port = $port; if(!empty($username)) { $this->_userName = base64_encode($username); } if(!empty($password)) { $this->_password = base64_encode($password); } return true; } /** * 設定發件人 * @access public * @param string $from 發件人地址 * @return boolean */ public function setFrom($from) { $this->_from = $from; return true; } /** * 設定收件人 * @access public * @param string $to 收件人地址 * @return boolean */ public function setReceiver($to) { $this->_to = $to; return true; } /** * 設定郵件資訊 * @access public * @param string $body 郵件主題 * @param string $subject 郵件主體內容,可以是純文字,也可是是HTML文字 * @return boolean */ public function setMailInfo($subject, $body) { $this->_subject = $subject; $this->_body = base64_encode($body); if(!empty($attachment)) { $this->_attachment = $attachment; } return true; } /** * 傳送郵件 * @access public * @return boolean */ public function sendMail() { $command = $this->getCommand(); $this->socket(); foreach ($command as $value) { if($this->sendCommand($value[0], $value[1])) { continue; } else{ return false; } } //其實這裡也沒必要關閉,smtp命令:QUIT發出之後,伺服器就關閉了連線,本地的socket資源會自動釋放 $this->close(); echo 'Mail OK!'; return true; } /** * 返回錯誤資訊 * @return string */ public function error(){ if(!isset($this->_errorMessage)) { $this->_errorMessage = ""; } return $this->_errorMessage; } /** * 返回mail命令 * @access protected * @return array */ protected function getCommand() { $separator = "----=_Part_" . md5($this->_from . time()) . uniqid(); //分隔符 $command = array( array("HELO sendmail\r\n", 250) ); if(!empty($this->_userName)){ $command[] = array("AUTH LOGIN\r\n", 334); $command[] = array($this->_userName . "\r\n", 334); $command[] = array($this->_password . "\r\n", 235); } //設定發件人 $command[] = array("MAIL FROM: <" . $this->_from . ">\r\n", 250); $header = "FROM: <" . $this->_from . ">\r\n"; //設定收件人 $command[] = array("RCPT TO: <" . $this->_to . ">\r\n", 250); $header .= "TO: <" . $this->_to . ">\r\n"; $header .= "Subject: " . $this->_subject ."\r\n"; $header .= "Content-Type: multipart/alternative;\r\n"; //郵件頭分隔符 $header .= "\t" . 'boundary="' . $separator . '"'; $header .= "\r\nMIME-Version: 1.0\r\n"; $header .= "\r\n--" . $separator . "\r\n"; $header .= "Content-Type:text/html; charset=utf-8\r\n"; $header .= "Content-Transfer-Encoding: base64\r\n\r\n"; $header .= $this->_body . "\r\n"; $header .= "--" . $separator . "\r\n"; //結束資料 $header .= "\r\n.\r\n"; $command[] = array("DATA\r\n", 354); $command[] = array($header, 250); $command[] = array("QUIT\r\n", 221); return $command; } /** * 傳送命令 * @access protected * @param string $command 傳送到伺服器的smtp命令 * @param int $code 期望伺服器返回的響應嗎 * @return boolean */ protected function sendCommand($command, $code) { echo 'Send command:' . $command . ',expected code:' . $code . '<br />'; //傳送命令給伺服器 try{ if(socket_write($this->_socket, $command, strlen($command))){ //當郵件內容分多次傳送時,沒有$code,伺服器沒有返回 if(empty($code)) { return true; } //讀取伺服器返回 $data = trim(socket_read($this->_socket, 1024)); echo 'response:' . $data . '<br /><br />'; if($data) { $pattern = "/^".$code."/"; if(preg_match($pattern, $data)) { return true; } else{ $this->_errorMessage = "Error:" . $data . "|**| command:"; return false; } } else{ $this->_errorMessage = "Error:" . socket_strerror(socket_last_error()); return false; } } else{ $this->_errorMessage = "Error:" . socket_strerror(socket_last_error()); return false; } }catch(Exception $e) { $this->_errorMessage = "Error:" . $e->getMessage(); } } /** * 建立到伺服器的網路連線 * @access private * @return boolean */ private function socket() { if(!function_exists("socket_create")) { $this->_errorMessage = "Extension sockets must be enabled"; return false; } //建立socket資源 $this->_socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp')); if(!$this->_socket) { $this->_errorMessage = socket_strerror(socket_last_error()); return false; } socket_set_block($this->_socket);//設定阻塞模式 //連線伺服器 if(!socket_connect($this->_socket, $this->_sendServer, $this->_port)) { $this->_errorMessage = socket_strerror(socket_last_error()); return false; } socket_read($this->_socket, 1024); return true; } /** * 關閉socket * @access private * @return boolean */ private function close() { if(isset($this->_socket) && is_object($this->_socket)) { $this->_socket->close(); return true; } $this->_errorMessage = "No resource can to be close"; return false; } }/**************************** Test ***********************************/ // $mail = new MySendMail(); // $mail->setServer("XXXX", "
[email protected]
", "XXXX"); // $mail->setFrom("[email protected]"); // $mail->setReceiver("[email protected]"); // $mail->setMailInfo("test", "<b>test</b>"); // $mail->sendMail(); ?>