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>
posted on 2016-12-30 15:50 coderWilson 阅读(2303) 评论(0) 编辑 收藏 举报