Evooms123's avatar

Limit the rate of emails sent with Laravel

Hello,

I am creating a forum with Laravel and as soon as a new private message or a new message in a thread where the user has participated, an email is sent. However, I have a problem: if a user receives 60 private message within an hour then he will receive 60 private message to notify him that he has a new message.

Is it possible to limit the number of emails sent per hour for example ? Is there a attribute to change somewhere ?

Here is an example of the function to find the recipient + send the private message in the MessagesController:

public function newPrivateMessage(Thread $thread, $urlToAccess){
        /* We retrieve the ID of the person connected */
        $userId = Auth::id();//auth()->user()->id
        /* We get the other user from the discussion. */
        $user = $thread->participants->where('user_id', '<>', $userId)->first();
        $userName = User::find($user->user_id);
        /* For the recipient, send an email */
        Mail::to($userName->email)->send(new NewPrivateMessageMail($user,$urlToAccess));
    }

And I've created a NewPrivateMessage inside my http folder with this artisan command php artisan make:mail NewPrivateMessage.

public function __construct($user,$urlToAccess)
{
    $this->data = $user;
    $this->url = $urlToAccess;
}

public function build()
{
    return $this
       ->subject('New private message')
       ->markdown('emails.markdown-newPrivateMessage');
}

Cordially

0 likes
5 replies
Evooms123's avatar

Hello, thanks for your help. I did this inside my RouteServiceProvider :

RateLimiter::for('mail', function(Request $request){
            return Limit::perHour(1)->response(function(){
               return response('Too much mail', 429);
            });
        });

And this to my route which is sending the email for a new PM :

  Route::get('{id}/sendNewPrivateMessage', [MessagesController::class, 'mailNewPrivateMessage'])->name('send.mail.new.private.message')->middleware('throttle:mail');

But still not worling... I did something wrong ?

Cordially

Houdinux's avatar

Hi, you found a way ? Would like to limit the number of mail someone can send.

Thanks in advance

Please or to participate in this conversation.