ThinkPHP5實現smtp發送郵件簡易實例

  1. 進入thinkphp5根目錄,使用composer安裝phpmailer:
    composer require phpmailer/phpmailer
  2. 簡單實例

    
    <?php
    namespace app\common\event;
    class EMail {
    
    function send($to, $name, $subject = '', $body = '', $attachment = null) {
        $mail = new \PHPMailer\PHPMailer\PHPMailer();           //實例化PHPMailer對象
        $mail->CharSet = 'UTF-8';           //設定郵件編碼,默認ISO-8859-1,如果發中文此項必須設置,否則亂碼
        $mail->IsSMTP();                    // 設定使用SMTP服務
        $mail->SMTPDebug = 1;               // SMTP調試功能 0=關閉 1 = 錯誤和消息 2 = 消息
        $mail->SMTPAuth = true;             // 啓用 SMTP 驗證功能
        $mail->SMTPSecure = 'ssl';          // 使用安全協議
        // $mail->Host = "smtp.exmail.qq.com"; // SMTP 服務器
        $mail->Host = "smtp.qq.com"; // SMTP 服務器
        $mail->Port = 465;                  // SMTP服務器的端口號
        $mail->Username = "[email protected]";    // SMTP服務器用戶名
        $mail->Password = "xxxx";     // SMTP服務器密碼
        $mail->SetFrom('[email protected]', '發送人名稱');
        $replyEmail = '';                   //留空則爲發件人EMAIL
        $replyName = '';                    //回覆名稱(留空則爲發件人名稱)
        $mail->AddReplyTo($replyEmail, $replyName);
        $mail->Subject = $subject;
        $mail->MsgHTML($body);
        $mail->AddAddress($to, $name);
        if (is_array($attachment)) { // 添加附件
            foreach ($attachment as $file) {
                is_file($file) && $mail->AddAttachment($file);
            }
        }
        return $mail->Send() ? true : true;//$mail->ErrorInfo;
    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章