首页 > 解决方案 > 如何检查邮件是否发送成功并在 laravel 通知中保存状态?

问题描述

我正在使用 laravel 通知发送电子邮件并保存到数据库。发送邮件后如何查看邮件状态以及如何保存在通知表中?

public function via($notifiable)
{
    return ['mail', DbChannel::class];
}

public function toMail($notifiable)
{
    return (new MailMessage)
        ->from('test@example.com', 'Example')
        ->line('...');
}

标签: laravellaravel-maillaravel-notification

解决方案


要处理这个问题,您可以定义 listener 和 event 。您首先在 App\Providers\EventServiceProvider 中注册它

protected $listen = [
    'App\Events\Event' => [
        'App\Listeners\EventListener',
    ],
    'Illuminate\Mail\Events\MessageSending' => [
        'App\Listeners\LogSendingMessage',
    ],
    'Illuminate\Mail\Events\MessageSent' => [
        'App\Listeners\LogSentMessage',
    ],
];

然后在 App\Listeners\LogSendingMessage 中,保存发送状态。例如

   public function handle(MessageSending $event)
{
    $notification = Notification::where('id',$event->data['notification']->id)->first();
    $notification->status = "Sending";
    $notification->save();
}

public function failed(MessageSending $event, $exception)
{
    $notification = Notification::where('id',$event->data['notification']->id)->first();
    $notification->status = "Sending Event Failed";
    $notification->save();
}

也适用于 LogSentMessage....有关更多信息,请参阅此链接 https://laravel.com/docs/8.x/mail#events


推荐阅读