laravel 邮件通知类使用
2018年9月1日1.创建新的邮件通知类
1 |
php artisan make:notification EmailVerificationNotification |
2.编辑邮件通知类
打开app\Notifications\EmailVerificationNotification.phpbi
编辑
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 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
<?php namespace App\Notifications; use Illuminate\Bus\Queueable; use Illuminate\Notifications\Notification; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Support\Str; #用与生成随机字符串的 use Cache; #用于缓存的 class EmailVerificationNotification extends Notification { use Queueable; /** * Create a new notification instance. * * @return void */ public function __construct() { // } /** * Get the notification's delivery channels. * * @param mixed $notifiable * @return array */ public function via($notifiable) { return ['mail']; } /** * Get the mail representation of the notification. * * @param mixed $notifiable * @return \Illuminate\Notifications\Messages\MailMessage */ public function toMail($notifiable) { $token = Str::random(32); #生成随机字符串 $url = route('email_verification.verify', ['email' => $notifiable->email, 'token' => $token]); #生成url Cache::set('email_verification_' . $notifiable->email, $token, 30); #缓存随机字符串设置缓存时间为30分钟 return (new MailMessage) ->greeting($notifiable->name . '您好:') ->subject('注册成功,请验证您的邮箱') ->line('请点击下方链接验证您的邮箱') ->action('验证', $url); } /** * Get the array representation of the notification. * * @param mixed $notifiable * @return array */ public function toArray($notifiable) { return [ // ]; } } |
3.使用邮件通知类
打开你要发送邮件的控制器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
use App\Notifications\EmailVerificationNotification; #引入用户激活邮箱的邮箱通知类 use Mail; #发送邮件的类 . . . public function send(Request $request) { $user = $request->user(); #获取请求用户的用户数据 if ($user->email_verified) { #判断用户是否激活 throw new Exception('你已经验证过邮箱了'); #如果激活告诉用户已经激活 } $user->notify(new EmailVerificationNotification()); #调用邮箱通知方法 return view('pages.success', ['msg' => '邮件发送成功']); #返回发送成功消息 } . . . |
4测试邮件发送
配置.env
1 2 3 4 5 6 |
MAIL_DRIVER=smtp MAIL_HOST=127.0.0.1 MAIL_PORT=1025 MAIL_USERNAME=null MAIL_PASSWORD=null MAIL_ENCRYPTION=null |
调用对应的邮件发送路由
打开http://<域名>:8025/
你就会看见你发送的邮件了