swiftmailer我就不介绍了,有兴趣的朋友可以自己找资料,下面主要是讲一下yii2如何通过swiftmailer来发email.
情景:通过发email找回密码
config文件夹里的配置文件,如main.php,配置如下:
-
'mail' => [
-
'class' => 'yii\swiftmailer\Mailer',
-
'viewPath' => '@common/mail',
-
//'useFileTransport' => true, //放在本地的邮件列表,测试邮件的时候可以开启这个
-
-
'transport' => [
-
'class' => 'Swift_SmtpTransport',
-
'host' => 'smtp.126.com',
-
'username' => 'your email',
-
'password' => 'password',
-
'port' => '465',
-
'encryption' => 'ssl',
-
-
],
-
-
],
controllers文件夹里的siteController.php,增加actionRequestPasswordReset,如下:
-
public function actionRequestPasswordReset() {
-
$model = new PasswordResetRequestForm();
-
-
if ($model->load(Yii::$app->request->post())) {
-
-
if ($model->sendEmail()) {
-
Yii::$app->getSession()->setFlash('success', 'Check your email for further instructions.');
-
return $this->goHome();
-
} else {
-
Yii::$app->getSession()->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
-
}
-
}
-
-
return $this->render('requestPasswordResetToken', [
-
'model' => $model,
-
]);
-
}
models文件夹里的
PasswordResetRequestForm.php文件,增加sendEmail函数,如下:
-
public function sendEmail()
-
{
-
/** @var User $user */
-
$user = User::find([
-
'status' => User::STATUS_ACTIVE,
-
'email' => $this->email,
-
]);
-
-
if (!$user) {
-
return false;
-
}
-
-
$user->generatePasswordResetToken();
-
if ($user->save()) {
-
return \Yii::$app->mail->compose()
-
->setFrom('from email')
-
->setTo('to email')
-
->setSubject('subject ')
-
->setTextBody('内容')
-
->send();
-
-
}
-
-
return false;
-
}
ok,相信经过上面的代码,你的邮件已经收到一封来自你自己发出的邮件了!
关于yii2 send email 的问题可以send email to 1017483952@qq.com探讨!
阅读(13409) | 评论(2) | 转发(0) |