Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

julianov's avatar

Send mail in a secondary thread

Hello everyone. The reason for the mail is how it is possible to send an electric mail in a secondary thread so as not to occupy processes in the main thread. For this purpose I have read that it is necessary to use the queque function of the Mail model.

This is the code I used:

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Ciudadano;

use Mail;

class CiudadanoController extends Controller

    public function store(Request $request)
    {

        $validated = $this->validate($request, [
            'cuil' => 'required',
            'nombre' => 'required',
            'apellido' => 'required',
            'email' => 'required',
            'password' => 'required',
        ]);

        $ciudadano = Ciudadano::create($validated);
        $ciudadano->save();

        Mail::queue('mail', ['name','Ripon Uddin Arman'], function ($message) {
            $message->from('[email protected]', 'Laravel');
            $message->to('[email protected]')->cc('[email protected]');
        });
        return "OK";
    }
 }

But I get this error output:

HTTP response: "Only mailables may be queued."

Why there is that problem?

0 likes
3 replies
rodrigo.pedra's avatar
Level 56

Well... Only mailables may be queued. The closure in your third parameter is not a mailable

A closure is hard to serialize to send as a mailable. Also when sent from within a class it would need to serialize all the current scope if the closure has a use (...) clause.

Create a new Mailable using php artisan make:mail MyMailable and adjust its content as you need.

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class MyMailable extends Mailable implements ShouldQueue
{
    use Queueable;
    use SerializesModels;

    public function build()
    {
        return $this->view('mail', ['name' => 'Ripon Uddin Arman']);
    }
}

And then queue it with

Mail::to('[email protected]')
    ->cc('[email protected]')
    ->queue((new MyMailable)->from('[email protected]', 'Laravel'));

References:

2 likes
rodrigo.pedra's avatar

@julianov

If you run the command php artisan make:mail MyMailable, the class will be created at your project's ./app/Mail directory, as hinted by the namespace on the code above.

If the directory does not exist, it will be created.

Note that MyMailable is an example, you can choose whichever name you want for your new class.

1 like

Please or to participate in this conversation.