天天看點

php通過smtp服務模拟用戶端發送email

剛進新公司項目用php開發的一個移動app商城項目,當時是需要做一個使用者新增賬號時,需要使用者在填寫郵箱時,背景擷取到填寫的郵箱,生成一個四位數的驗證碼,發送到該郵箱,郵箱發送成功後,再将這個驗證碼傳回給前台,前台頁面拿到這個驗證碼後會去判斷使用者輸入的這個驗證碼是否是背景發送的這個驗證碼。目的就是為了防止使用者注冊時候胡亂填寫郵箱

好吧上代碼。這裡主要注意的是2個地方,1個是發件箱的内容和标題的編碼格式。我是直接在它方法開始時直接設定編碼格式為utf-8,還有一個地方就是設定smtp密碼時,無論你是163還是qq郵箱作為發件人,必須登陸郵箱裡面開啟smtp服務,現在的smtp服務都需要開啟用戶端的授權碼,是以你在填寫smtp伺服器密碼時,必須是填寫用戶端授權碼,而不是你的密碼

qq郵箱開啟smtp服務的地方,點選開啟,qq郵箱會跟你一個用戶端的授權碼,記得拿這個授權碼作為登陸密碼就ok了

php通過smtp服務模拟用戶端發送email

我試過用163新注冊的賬号,開通smtp服務發送郵件,但是無論怎麼樣都沒有成功,一直提示我身份證驗證錯誤,換成郵箱登陸密碼也沒用,後面試着用自己以前的賬号發送一下就成功了,是以基本排除了代碼的問題

//發送郵件和生成驗證碼
public function emailVlidateAction(){
    header("Content-Type: text/html;charset=utf-8");
    $email = $this->params()->fromQuery('email','[email protected]');

    if($email){
        //生成四位數随機驗證碼
        $token =  rand(1000,9999);
        //發送郵件
        $isSend = $this->smtpService($email,$token);
        //傳回給前端驗證碼
        if($isSend === true){
            return new JsonModel(['status'=>200,'message'=>'請求成功!','data'=>$token]);
        }else{
            return new JsonModel(['status'=>202,'message'=>'郵件發送失敗,請稍後再試!']);
        }
    }else{
        echo "使用者email不能為空";
    }
}

public function smtpService($email,$token){

     $MailPort = 25; //SMTP服務端口
     $MailServer = "smtp.qq.com";
     $smtpMail = "[email protected]"; //SMTP郵箱賬号
     $smtpuser = "xxxx"; //SMTP伺服器賬号
     $smtppass = "xxxx"; //SMTP伺服器密碼,除非是老版本注冊的郵箱,否則現在申請的都需要用用戶端授權碼作為密碼!!!

    //建立一個smtp服務對象, true是對發件人身份證驗證
    $smtp = new Smtp($MailServer, $MailPort, $smtpuser, $smtppass, true);

    $smtp->debug = false;
    //設定請求内容格式
    $mailType = "HTML";
    //收件人郵箱
    $email = $email;
    //标題
    $emailTitle = "郵箱驗證碼";
    $emailBody = ""."親愛的使用者<br/>您的郵箱驗證碼是:".$token."<br/>如非本人發送的請求,請忽略此郵件.<br/>";
    // 收件人郵箱
    // 發件人郵箱
    // 郵箱标題
    // 郵箱内容
    // 郵件内容内型如:text 、:HTML
    return $smtp->sendmail($email, $smtpMail, $emailTitle, $emailBody, $mailType);
}      

smtp類

<?php

class Smtp
{
    /* Public Variables */
    var $smtp_port; //smtp_port 端口号
    var $time_out;
    var $host_name; //伺服器主機名
    var $log_file;
    var $relay_host; //伺服器主機位址
    var $debug;
    var $auth; //驗證
    var $user; //伺服器使用者名
    var $pass; //伺服器密碼
    /* Private Variables */
    var $sock;
    /* Constractor 構造方法*/

    function __construct($relay_host = "", $smtp_port = 25, $user, $pass, $auth = false)
    {
        $this->debug      = FALSE;
        $this->smtp_port  = $smtp_port;
        $this->relay_host = $relay_host;
        $this->time_out   = 30; //is used in fsockopen()
        #
        $this->auth       = $auth; //auth
        $this->user       = $user;
        $this->pass       = $pass;
        #
         $this->host_name  = "localhost"; //is used in HELO command
        // $this->host_name = "smtp.163.com"; //is used in HELO command

        $this->log_file   = "";
        $this->sock = FALSE;

    }

    /* Main Function */
    function sendmail($to, $from, $subject = "", $body = "", $mailtype, $cc = "", $bcc = "", $additional_headers = "")

    {
        $header    = "";
        $mail_from = $this->get_address($this->strip_comment($from));
        $body      = mb_ereg_replace("(^|(\r\n))(\\.)", "\\1.\\3", $body);
        $header .= "MIME-Version:1.0\r\n";
        if ($mailtype == "HTML") { //郵件發送類型
            //$header .= "Content-Type:text/html\r\n";
            $header .= 'Content-type: text/html; charset=utf-8' . "\r\n";
        }
        $header .= "To: " . $to . "\r\n";
        if ($cc != "") {
            $header .= "Cc: " . $cc . "\r\n";
        }

        $header .= "From: " . $from . "\r\n";
        // $header .= "From: $from<".$from.">\r\n";    //這裡隻顯示郵箱位址,不夠人性化

        $header .= "Subject: " . $subject . "\r\n";
        $header .= $additional_headers;
        $header .= "Date: " . date("r") . "\r\n";
        $header .= "X-Mailer:By (PHP/" . phpversion() . ")\r\n";

        list($msec, $sec) = explode(" ", microtime());

        $header .= "Message-ID: <" . date("YmdHis", $sec) . "." . ($msec * 1000000) . "." . $mail_from . ">\r\n";
        $TO = explode(",", $this->strip_comment($to));

        if ($cc != "") {
            $TO = array_merge($TO, explode(",", $this->strip_comment($cc))); //合并一個或多個數組
        }

        if ($bcc != "") {
            $TO = array_merge($TO, explode(",", $this->strip_comment($bcc)));
        }

        $sent = TRUE;

        foreach ($TO as $rcpt_to) {
            $rcpt_to = $this->get_address($rcpt_to);

            if (!$this->smtp_sockopen($rcpt_to)) {
                 $this->log_write("Error: Cannot send email to " . $rcpt_to . "\n");
                 $sent = FALSE;
                continue;

            }

            if ($this->smtp_send($this->host_name, $mail_from, $rcpt_to, $header, $body)) {
                 $this->log_write("E-mail has been sent to <" . $rcpt_to . ">\n");
            } else {

                 $this->log_write("Error: Cannot send email to <" . $rcpt_to . ">\n");
                $sent = FALSE;

            }

            fclose($this->sock);
            $this->log_write("Disconnected from remote host\n");
        }
        return $sent;
    }

    /* Private Functions */
    function smtp_send($helo, $from, $to, $header, $body = "")
    {

        if (!$this->smtp_putcmd("HELO", $helo)) {
            return $this->smtp_error("sending HELO command");
        }

        if ($this->auth) {

            if (!$this->smtp_putcmd("AUTH LOGIN", base64_encode($this->user))) {
                 return $this->smtp_error("sending HELO command");
            }
            if (!$this->smtp_putcmd("", base64_encode($this->pass))) {
                return $this->smtp_error("sending HELO command");
            }
         }

        if (!$this->smtp_putcmd("MAIL", "FROM:<" . $from . ">")) {
            return $this->smtp_error("sending MAIL FROM command");
        }

        if (!$this->smtp_putcmd("RCPT", "TO:<" . $to . ">")) {
            return $this->smtp_error("sending RCPT TO command");
        }

        if (!$this->smtp_putcmd("DATA")) {
            return $this->smtp_error("sending DATA command");
        }

        if (!$this->smtp_message($header, $body)) {
            return $this->smtp_error("sending message");
        }

        if (!$this->smtp_eom()) {
            return $this->smtp_error("sending <CR><LF>.<CR><LF> [EOM]");
        }

        if (!$this->smtp_putcmd("QUIT")) {
            return $this->smtp_error("sending QUIT command");
        }

        return TRUE;
    }

    function smtp_sockopen($address)
    {

        if ($this->relay_host == "") {
            return $this->smtp_sockopen_mx($address);
        } else {
            return $this->smtp_sockopen_relay();
        }
    }

    function smtp_sockopen_relay()
    {
        $this->log_write("Trying to " . $this->relay_host . ":" . $this->smtp_port . "\n");
        $this->sock = @fsockopen($this->relay_host, $this->smtp_port, $errno, $errstr, $this->time_out);

        if (!($this->sock && $this->smtp_ok())) {

            $this->log_write("Error: Cannot connenct to relay host " . $this->relay_host . "\n");
            $this->log_write("Error: " . $errstr . " (" . $errno . ")\n");
            return FALSE;

        }
        $this->log_write("Connected to relay host " . $this->relay_host . "\n");
        return TRUE;
    }

    function smtp_sockopen_mx($address)
    {
        $domain = ereg_replace("^.+@([^@]+)$", "\\1", $address);

        if (!@getmxrr($domain, $MXHOSTS)) {

            $this->log_write("Error: Cannot resolve MX \"" . $domain . "\"\n");
            return FALSE;

        }

        foreach ($MXHOSTS as $host) {

            $this->log_write("Trying to " . $host . ":" . $this->smtp_port . "\n");
            $this->sock = @fsockopen($host, $this->smtp_port, $errno, $errstr, $this->time_out);

            if (!($this->sock && $this->smtp_ok())) {

                $this->log_write("Warning: Cannot connect to mx host " . $host . "\n");
                $this->log_write("Error: " . $errstr . " (" . $errno . ")\n");
                continue;
            }

            $this->log_write("Connected to mx host " . $host . "\n");
            return TRUE;

        }

        $this->log_write("Error: Cannot connect to any mx hosts (" . implode(", ", $MXHOSTS) . ")\n");
        return FALSE;

    }

    function smtp_message($header, $body)

    {
        fputs($this->sock, $header . "\r\n" . $body);
        $this->smtp_debug("> " . str_replace("\r\n", "\n" . "> ", $header . "\n> " . $body . "\n> "));
        return TRUE;
    }

    function smtp_eom()
    {
        fputs($this->sock, "\r\n.\r\n");
        $this->smtp_debug(". [EOM]\n");
        return $this->smtp_ok();
    }

    function smtp_ok()
    {
        $response = str_replace("\r\n", "", fgets($this->sock, 512));
        $this->smtp_debug($response . "\n");
         if (!mb_ereg("^[23]", $response)) {
            fputs($this->sock, "QUIT\r\n");
            fgets($this->sock, 512);
            $this->log_write("Error: Remote host returned \"" . $response . "\"\n");
            return FALSE;
        }
        return TRUE;
    }

    function smtp_putcmd($cmd, $arg = "")
    {

        if ($arg != "") {
            if ($cmd == "")
                $cmd = $arg;
            else
                $cmd = $cmd . " " . $arg;

        }

        fputs($this->sock, $cmd . "\r\n");
        $this->smtp_debug("> " . $cmd . "\n");
        return $this->smtp_ok();

    }

    function smtp_error($string)
    {
        $this->log_write("Error: Error occurred while " . $string . ".\n");
        return FALSE;
    }

    function log_write($message)
    {
        $this->smtp_debug($message);

        if ($this->log_file == "") {
            return TRUE;
        }



        $message = date("M d H:i:s ") . get_current_user() . "[" . getmypid() . "]: " . $message;

        if (!@file_exists($this->log_file) || !($fp = @fopen($this->log_file, "a"))) {

            $this->smtp_debug("Warning: Cannot open log file \"" . $this->log_file . "\"\n");
            return FALSE;
        }

        flock($fp, LOCK_EX);
        fputs($fp, $message);
        fclose($fp);

        return TRUE;
    }

    function strip_comment($address)
    {
        $comment = "\\([^()]*\\)";

        while (mb_ereg($comment, $address)) {

            $address = mb_ereg_replace($comment, "", $address);
        }
        return $address;
    }

    function get_address($address)
    {

        $address = mb_ereg_replace("([ \t\r\n])+", "", $address);
        $address = mb_ereg_replace("^.*<(.+)>.*$", "\\1", $address);
        return $address;
    }

    function smtp_debug($message)
    {

        if ($this->debug) {
            echo $message . "<br>";
        }
    }

}