如何在 make:auth 之后用 QQ 邮箱发送自定义密码重置邮件?
生成授权码
使用 Laravel 发送 QQ 邮件使用的不是 QQ 邮箱号和密码,而是 QQ 邮箱号和授权码(QQ 推出的用于登录第三方客户端的专用密码)。生成授权码的步骤如下:
进入 QQ 邮箱网页版 → 设置 → 账户 → (开启)POP3/SMTP 服务 → (点击)生成授权码
需要注意的是,授权码一定要妥善保存,避免因为泄露带来不必要的麻烦!
配置 .env
APP_URL=http://homestead.app
MAIL_DRIVER=smtp
MAIL_HOST=smtp.qq.com
MAIL_PORT=465
MAIL_USERNAME=邮箱号
MAIL_PASSWORD=授权码
MAIL_ENCRYPTION=ssl
MAIL_FROM_ADDRESS=${MAIL_USERNAME}
MAIL_FROM_NAME=测试邮件
将 「邮箱号」、「授权码」换成你的就可以了。
创建邮件
$ php artisan make:mail ResetPassword --markdown
修改 ResetPassword.php
:
<?php
namespace App\Mail;
use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Queue\ShouldQueue;
class ResetPassword extends Mailable
{
use Queueable, SerializesModels;
public $token;
public $username;
/**
* Create a new message instance.
*
* @return void
*/
public function __construct($token, $username)
{
$this->token = $token;
$this->username = $username;
}
/**
* Build the message.
*
* @return $this
*/
public function build()
{
return $this->subject('密码重置')
->markdown('emails.reset_password');
}
}
邮件内容在 views/emails/reset_password.blade.php
,现在创建它。
@component('mail::message')
# 重置密码
你好,{{ $username }}!点击下面的链接,重置密码
@component('mail::button', ['url' => url(config('app.url').route('password.reset', $token, false))])
重置密码
@endcomponent
如果非本人操作,请忽略这封邮件。
你的,<br>
{{ config('app.name') }}
@endcomponent
重写发送密码重置邮件的方法
Laravel 内置有发送邮件功能,最终发送邮件的方法是调用 Illuminate\Auth\Passwords\CanResetPassword
这个 trait 的 sendPasswordResetNotification
方法。
/**
* Send the password reset notification.
*
* @param string $token
* @return void
*/
public function sendPasswordResetNotification($token)
{
$this->notify(new ResetPassword($token));
}
User Model 使用了这个 trait,所以在 User Model 中重写 sendPasswordResetNotification
方法就可以将密码重置邮件更改为我们刚才自定义的。
下面为 User Model 添加方法 sendPasswordResetNotification
:
use Mail;
use App\Mail\ResetPassword;
public function sendPasswordResetNotification($token)
{
Mail::to($this->email)->send(new ResetPassword($token, $this->name));
}
现在,访问地址 http://homestead.app/password/reset 就能看到用我们的 QQ 邮箱发送自定义密码重置邮件了。
本作品采用《CC 协议》,转载必须注明作者和本文链接
你好,我的报错
Connection could not be established with host smtp.mailtrap.io :stream_socket_client(): SSL operation failed with code 1. OpenSSL Error messages: error:1408F10B:SSL routines:ssl3_get_record:wrong version number
,请问这无法连接是由于ssl,要如何解决 :flushed: