Laravel
里我们可以使用php artisan make:auth
来生成一套默认的登陆注册重置邮箱的Authentication System
,但是如何修改系统发送给用户的重置密码邮件的样式和内容呢?
虽然默认的邮件样式很美观,但是不免全部是英文,我们至少可以添加进一些中文提示,方便用户查看。
首先我们需要明确的是:
- Laravel 默认的 Notification Class是ResetPassword,位于
Illumintate/Auth/Notifications
中。- 我们不应该直接修改位于ResetPassword里的代码,因为如果更新package可能导致覆盖。
我们先来看一下ResetPassword
:
<?php
namespace IlluminateAuthNotifications;
use IlluminateNotificationsNotification;
use IlluminateNotificationsMessagesMailMessage;
class ResetPassword extends Notification
{
public $token;
public function __construct($token)
{
$this->token = $token;
}
public function via($notifiable)
{
return ['mail'];
}
public function toMail($notifiable)
{
return (new MailMessage)
->line('You are receiving this email because we received a password reset request for your account')
->action('Reset Password', url(config('app.url').route('password.reset', $this->token, false)))
->line('If you did not request a password reset, no further action is required.');
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
可以看到,ResetPassword
拓展了Notification
这个类,所以我们需要做的就是新建一个Notification
类,来完成我们自定义邮件内容的修改:
$ php artisan make:notification ResetPasswordNotification
- 1
输入以上artisan
命令,我们会发现在AppNotifications
文件夹下多出了一个名为ResetPasswordNotification.php
的文件,打开它,我们可以看到其内容跟ResetPassword
很相似。我们只需要修改关键的代码即可:
<?php
namespace IlluminateAuthNotifications;
use IlluminateBusQueueable;
use IlluminateNotificationsNotification;
use IlluminateContractsQueueShouldQueue;
use IlluminateNotificationsMessagesMailMessage;
class ResetPasswordNotification extends Notification
{
use Queueable;
public $token;
public function __construct($token)
{
$this->token = $token;
}
public function via($notifiable)
{
return ['mail'];
}
public function toMail($notifiable)
{
return (new MailMessage)
->line('这里可以放我们需要添加的内容')
->line('You are receiving this email because we received a password reset request for your account')
->action('Reset Password', url(config('app.url').route('password.reset', $this->token, false)))
->line('这里可以放我们需要添加的内容')
->line('If you did not request a password reset, no further action is required.');
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
可以看到,我们可以以line作为单位来添加我们需要的信息。
那么信息内容搞定了,怎么样修改邮件样式呢?首先我们需要能够修改信息的Blade
模板:
$ php artisan vendor:publish --tag=laravel-notifications
- 1
以上命令把包裹里的模板发布到resources/views/vendor/notifications
文件夹中,这样我们只需要修改resources/views/vendor/notifications/email.blade.php
就可以了。
最后一步,我们在User
模型里添加:
/**
* Send the password reset notification.
*
* @param string $token
* @return void
*/
public function sendPasswordResetNotification($token)
{
$this->notify(new ResetPasswordNotification($token));
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
这样,我们就可以使用ResetPasswordNotification
来进行邮件的发送了。
模板的修改很简单,这里就不赘述了,完成后,我们可以看到新的邮件内容: