php socket 기반 SMTP 메 일 보 내 는 방법

13042 단어 phpsocketSMTP우편물
이 실례 는 php 가 socket 을 바탕 으로 SMTP 가 메 일 을 보 내 는 방법 을 설명 한다.모두 에 게 참고 하도록 공유 하 다.구체 적 인 분석 은 다음 과 같다.
php 는 socket 을 사용 하여 SMTP 를 통 해 메 일 을 보 냅 니 다.
phop 의 phop-sockets 확장 을 사용 하여 일반 텍스트 와 html 형식의 메 일 을 보 낼 수 있 습 니 다.코드 는 다음 과 같 습 니 다:

<?php
/**
*
* HTML
* @example
* $config = array(
*       "from" => "*****",
*       "to" => "***",
*       "subject" => "test",
*       "body" => "<b>test</b>",
*       "username" => "***",
*       "password" => "****",
*       "isHTML" => true
*   );
*
* $mail = new MySendMail();
*
* $mail->setServer("smtp.126.com");
*
* $mail->setMailInfo($config);
* if(!$mail->sendMail()) {
*   echo $mail->error();
*   return 1;
* }
*/
class MySendMail {
    /**
    * @var
    * @access private
    */
    private $_userName;
    /**
    * @var
    * @access private
    */
    private $_password;
    /**
    * @var
    * @access protected
    */
    protected $_sendServer;
    /**
    * @var
    * @access protected
    */
    protected $_port=25;
    /**
    * @var
    * @access protected
    */
    protected $_from;
    /**
    * @var
    * @access protected
    */
    protected $_to;
    /**
    * @var
    * @access protected
    */
    protected $_subject;
    /**
    * @var
    * @access protected
    */
    protected $_body;
    /**
    * @var HTML
    * @access protected
    */
    protected $_isHTML=false;
    /**
    * @var socket
    * @access protected
    */
    protected $_socket;
    /**
    * @var
    * @access protected
    */
    protected $_errorMessage;
    public function __construct($from="", $to="", $subject="", $body="", $server="", $username="", $password="",$isHTML="", $port="") {
        if(!empty($from)){
            $this->_from = $from;
        }
        if(!empty($to)){
            $this->_to = $to;
        }
        if(!empty($subject)){
            $this->_subject = $subject;
        }
        if(!empty($body)){
            $this->_body = $body;
        }
        if(!empty($isHTML)){
            $this->_isHTML = $isHTML;
        }
        if(!empty($server)){
            $this->_sendServer = $server;
        }
        if(!empty($port)){
            $this->_port = $port;
        }
        if(!empty($username)){
            $this->_userName = $username;
        }
        if(!empty($password)){
            $this->_password = $password;
        }
    }
    /**
    *
    * @param string $server ip
    * @param int $port ,smtp 25
    * @param int $localPort
    * @return boolean
    */
    public function setServer($server, $port=25) {
        if(!isset($server) || empty($server) || !is_string($server)) {
            $this->_errorMessage = "first one is an invalid parameter";
            return false;
        }
        if(!is_numeric($port)){
            $this->_errorMessage = "first two is an invalid parameter";
            return false;
        }
        $this->_sendServer = $server;
        $this->_port = $port;
        return true;
    }
    /**
    *
    * @access public
    * @param array $config
    * 、 、 、 、
    * @return boolean
    */
    public function setMailInfo($config) {
        if(!is_array($config) || count($config) < 6){
            $this->_errorMessage = "parameters are required";
            return false;
        }
        $this->_from = $config['from'];
        $this->_to = $config['to'];
        $this->_subject = $config['subject'];
        $this->_body = $config['body'];
        $this->_userName = $config['username'];
        $this->_password = $config['password'];
        if(isset($config['isHTML'])){
            $this->_isHTML = $config['isHTML'];
        }
        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;
            }
        }
        $this->close(); // ,smtp :QUIT , , socket
        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() {
        if($this->_isHTML) {
            $mail = "MIME-Version:1.0\r
";
            $mail .= "Content-type:text/html;charset=utf-8\r
";
            $mail .= "FROM:test<" . $this->_from . ">\r
";
            $mail .= "TO:<" . $this->_to . ">\r
";
            $mail .= "Subject:" . $this->_subject ."\r
\r
";
            $mail .= $this->_body . "\r
.\r
";
        }
        else{
            $mail = "FROM:test<" . $this->_from . ">\r
";
            $mail .= "TO:<" . $this->_to . ">\r
";
            $mail .= "Subject:" . $this->_subject ."\r
\r
";
            $mail .= $this->_body . "\r
.\r
";
        }
        $command = array(
                array("HELO sendmail\r
", 250),
                array("AUTH LOGIN\r
", 334),
                array(base64_encode($this->_userName) . "\r
", 334),
                array(base64_encode($this->_password) . "\r
", 235),
                array("MAIL FROM:<" . $this->_from . ">\r
", 250),
                array("RCPT TO:<" . $this->_to . ">\r
", 250),
                array("DATA\r
", 354),
                array($mail, 250),
                array("QUIT\r
", 221)
        );
        return $command;
    }
    /**
    * @access protected
    * @param string $command smtp
    * @param int $code
    * @param boolean
    */
    protected function sendCommand($command, $code) {
        echo 'Send command:' . $command . ',expected code:' . $code . '<br />';
        //
        try{
            if(socket_write($this->_socket, $command, strlen($command))){
                //
                $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 php-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;
        }
        //
        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 ***********************************/
$config = array(
        "from" => "XXXXX",
        "to" => "XXXXX",
        "subject" => "test",
        "body" => "<b>test</b>",
        "username" => "XXXXX",
        "password" => "******",
        //"isHTML" => true
    );
$mail = new MySendMail();
$mail->setServer("smtp.126.com");
$mail->setMailInfo($config);
if(!$mail->sendMail()) {
    echo $mail->error();
    return 1;
}
본 논문 에서 말 한 것 이 여러분 의 phop 프로 그래 밍 에 도움 이 되 기 를 바 랍 니 다.

좋은 웹페이지 즐겨찾기