yii2.0 框架邮件的发送
第一步:
在main-local.php中的components中配置mailer:
$config = [ 'components' => [ 'mailer' => [ 'class' => 'yii\swiftmailer\Mailer', 'viewPath' => '@common/mail', 'useFileTransport' => false, 'transport' => [ 'class' => 'Swift_SmtpTransport', 'host' => 'mail2.augmentum.com.cn', 'username' => 'gladysyang@augmentum.com.cn', 'password'=> '111111', 'port' => '25',//这个可以在网上搜,一般的smtp服务器端口为25 'encryption' => '', ], 'messageConfig' => [ 'charset' => 'UTF-8', 'from' => ['gladysyang@augmentum.com.cn'=>'admin'] ], ], ], ];
第二步:配置params.php文件(*这个好像不用配置也行,我也是初学者,有点搞不懂,反正配置了也没有影响)
<?php return [ 'adminEmail' => 'gladysyang@augmentum.com.cn', 'supportEmail' => 'gladysyang@augmentum.com.cn', 'user.passwordResetTokenExpire' => 3600, ];
第三步:在model类里面用EmailValidator类验证邮箱地址格式
//验证邮箱 public function emailValidator($email) { $validator = new EmailValidator(); if ($validator->validate($email, $error)) { return 'success'; } else { return $error; } }
第四步:在controller中发送邮件
//忘记密码 public function actionForget() { $request = Yii::$app->request; $emailAddress = $request->post('email'); //调用User类中的emailValidator方法,判断用户输入的邮箱地址格式是否正确 $message = User::emailValidator($emailAddress); if ($message === 'success') { //如果邮箱地址格式正确,写邮箱内容 $mail = Yii::$app->mailer->compose(); $mail->setTo($emailAddress); $mail->setSubject('找回密码'); $mail->setHtmlBody('<font>please click this link</font><br><a href="">iajeijfajfkajfdkjfjdf</a>'); try { //发送邮件 if ($mail->send()) { //如果邮件发送成功,解析邮箱地址,拼接成一个url $emailArr = explode("@", $emailAddress); $emailUrl = 'https://mail.' . $emailArr[1]; //然后判断url是否存在 if ($this->url_exists($emailUrl)) { //如果存在,我在邮件发送成功界面出现一个链接 $data['url'] = $emailUrl; return $this->render('success', $data); } //否则直接跳到邮件发送成功界面 return $this->render('success'); } // "\"默认在系统中找Swift_TransportException } catch (\Swift_TransportException $e) { $data['message'] = '邮件发送失败,请检查网络是否正常'; return $this->render('forget', $data); } } else { //如果输入的邮箱错误,还是回到发送邮箱界面 return $this->render('forget', ['message'=>'请输入正确的邮箱']); } } //判断网址是否存在 public function url_exists($url) { $check = @fopen($url,"r"); if($check) $status = true; else $status = false; return $status; }
注:这些只是我在写demo时记下的,如有不对的地方,忘指教