yii2 郵件發送(有圖有真相)


經典的密碼找回方案是發送郵件到用戶郵箱然后修改密碼,下面利用yii2 高級版的mail功能,進行郵件的發送,如下圖

1.在comm/config/main-local.php中添加

'mailer' =>[
            'class' => 'yii\swiftmailer\Mailer',
            'viewPath' => '@common/mail', //指定郵件模版路徑
            //false:非測試狀態,發送真實郵件而非存儲為文件
            'useFileTransport' => false,
            'transport'=>[
                'class' => 'Swift_SmtpTransport',
                'host' =>'smtp.163.com',              //163郵箱的SMTP服務器: smtp.163.com
                'username' => 'coder_wilson@163.com',
                'password' => 'xxxxxx',          //163郵箱的客戶端授權密碼
                'port' => '465',
                'encryption' => 'ssl',
            ],
            ], 

2.在對應的controller中的代碼片段如下

 public function actionSeekpassword(){
        $model=new User;
        $model->setScenario('seekpassword');
     //對表單提交用戶名和郵箱進行數據庫驗證
if($model->certificate($data)){
        //調用發送郵件函數
if($model->seekPass()){ return $this->success(['site/seekpassword']); }else{ $message=current($model->getFirstErrors()); return $this->error($message); } } return $this->render("seekpassword",[ 'model'=>$model, ]); }

3.對應的model中代碼片段如下

 public function seekpass(){        
     $data=Yii::$app->request->post('User');       
     $time=time();
        $token=$this->createToken($data['username'],$time);
        //里面參數代表指定模版和傳遞的參數  common/mail/layouts/html里面有模版了寫主體就行了
        $mailer= Yii::$app->mailer->compose('seekpass',['username'=>$data['username'],'time'=>$time,'token'=>$token]); 
        $mailer->setFrom("coder_wilson@163.com");
        $mailer->setTo($data['email']);
        $mailer->setSubject("找回密碼");//郵件主題標題
        if($mailer->send()){
            return true;
        }else{
            return false;
        }
}

4.view文件與普通表單文件無異

5.common/mail/seekpass發送郵件的模版文件

<p>尊敬的:<b><?php echo $username; ?></b></p>
<p>您找回密碼的鏈接如下:</p>
<?php $url=Yii::$app->urlManager->createAbsoluteUrl(['site/reback','time'=> $time,'username'=>$username,'token'=>$token]); ?>
<p><a href="<?php echo $url; ?>"><?php echo $url; ?></a></p>
<p>該鏈接5分鍾內有效,請勿傳遞給別人</p>
<p>該郵件為系統自動發送,請勿回復!!</p>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM