如何在 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=25
MAIL_USERNAME=邮箱号
MAIL_PASSWORD=授权码
MAIL_ENCRYPTION=ssl
MAIL_FROM_ADDRESS=${MAIL_USERENAME}
MAIL_FROM_NAME=测试邮件

将 「邮箱号」、「授权码」换成你的就可以了。

创建邮件

php artisan make:mail ResetPassword --markdown

修改 ResetPassword.php

<?php

namspace 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.botten', ['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 senPasswordResetNotification($token)
{
     $this->notify(new ResetPassword($token));
}

User Model 使用了这个 trait ,所以在 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));
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 原文链接 必备品 文档:Documentation API:API Reference 视频:Laracasts ...
    layjoy阅读 8,630评论 0 121
  • Laravel 学习交流 QQ 群:375462817 本文档前言Laravel 文档写的很好,只是新手看起来会有...
    Leonzai阅读 8,086评论 2 12
  • 22年12月更新:个人网站关停,如果仍旧对旧教程有兴趣参考 Github 的markdown内容[https://...
    tangyefei阅读 35,241评论 22 257
  • 小蜗牛一直拉着我的手,早上穿过树林去上学,下午接了她踩着晚霞去回家。我的小蜗牛很调皮,牵着她的手一走就是五年,每一...
    海深深阅读 468评论 1 3
  • 入伏几天了,闷热自不必说,邵童鞋进门儿就嚷嚷着热啊热啊。下过一场场雷震雨的小城,依旧流动着温暖到爆的空气,热啊热。...
    薇安妮阅读 174评论 0 0