0

I have Laravel 10 as my API backend with Fortify. When resetting the password, I want to send HTML content (retrieved from the database) to an email. The email should be queued, possibly via the jobs table.

In FortifyServiceProvider, I have tried the toMailUsing method.

ResetPassword::toMailUsing(function (User $user, string $token) {
    return (new ResetEmail($user, $token))->onQueue('send-email');
});

But this email needs to be queued and sent directly.

FYI: I am already running send-email queue to send other emails, and it is working perfectly fine (via Jobs). And yes, I do have set this in .env QUEUE_CONNECTION=database

In laravel source i have found this:

if ($message instanceof Mailable) {
    return $message->send($this->mailer);
}

This is supposed to handle the queued Mailable as well, right? Or am I heading in the wrong direction?

Source:10.x/src/Illuminate/Notifications/Channels/MailChannel.php#L63

1 Answer 1

0

Fixed with these changes.

  1. Created notification table with
php artisan notifications:table
 
php artisan migrate
  1. Created custom notification class
<?php

namespace App\Notifications;

use App\Models\User;
use App\Mail\ResetEmail;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;

class ResetEmailNotificationQueued extends Notification implements ShouldQueue
{
    use Queueable;

    /**
     * Create a new notification instance.
     */
    public function __construct(private string $token)
    {
        $this->onQueue('send-email');
    }

    /**
     * Get the notification's delivery channels.
     *
     * @return array<int, string>
     */
    public function via(object $notifiable): array
    {
        return ['mail'];
    }

    /**
     * 
     * @param User $notifiable
     * 
     * Get the mail representation of the notification.
     */
    public function toMail(object $notifiable): Mailable
    {
        return new ResetEmail($notifiable, $this->token);
    }
}

  1. Updated Models\User.php
public function sendPasswordResetNotification($token)
{
    $this->notify(new ResetEmailNotificationQueued($token));
}
  1. Run queue
php artisan queue:listen --queue=default,send-email

Cheers :).

Sign up to request clarification or add additional context in comments.

1 Comment

ResetEmail is mailable class under app namespace, so probably we can update this mailable to queue this email. see laravel.com/docs/master/mail#queueing-mail.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.