send email to multiple users in laravel

Send email to multiple users using Queue in Laravel

Today, I will give you an example of “How to send email to multiple users using Queue in Laravel”, So you can easily apply it with your laravel 5, laravel 6, laravel 7, and laravel 8 application.

First, what we’re doing here, This is the example :

send email to all users using queue in laravl

send email to bulk users in laravel

mailtrap configuration in laravel

Queue in Laravel

Laravel queues provide a unified API across various queue backends, such as Beanstalk, Amazon SQS, Redis, or even a relational database. As a result, queues allow you to defer the processing of a time-consuming task, such as sending an email. Delaying these time-consuming tasks drastically speeds up web requests to your application.

Queue Configuration in Laravel

The queue configuration file is stored in config/queue.php In this file, you will find connection configurations for each of the queue drivers included with the framework, which consists of a database, Beanstalkd, Amazon SQS, Redis, and synchronous driver that will execute jobs immediately (for local use). In addition, a null queue driver is also included, which discards queued jobs.

Create migration and queue table

We need to create queue table. Run the below commands one by one to create queue table.

php artisan queue:table
php artisan migrate
jobs table in queue in laravel
failed_jobs table in queue in laravel

Configure Queue Driver

We need to select a queue driver and need to generate a queues table. There are some drivers available such as sync, database, redis, sqs etc. We are going to use database driver to Send email to multiple users in Laravel application.

Finally, don’t forget to instruct your application to use the database driver by updating the QUEUE_CONNECTION variable in your application’s .env file:

.env

QUEUE_CONNECTION=database

Add SMTP Details in .env File

We will use Mailtrap Server to send Emails in Laravel, you can use Gmail or other testing SMTP servers.

mailtrap inbox

.env


MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=465
MAIL_USERNAME=yourmailtrapusername
MAIL_PASSWORD=yourmailtrappassword
MAIL_ENCRYPTION=tls
MAIL_FROM_NAME="${APP_NAME}"

Send email to all users Example

Now we will create a product add file, whenever we add any product the product will be store in products table and it will send the product information to all users email from users table.

Users Table Data

In the users table we have some users with testing emails for send email to all users.

send email to all users in laravel

Create a Controller

php artisan make:controller TestEmailJobController

Define Web Routes

routes\web.php

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/test-email-create','TestEmailJobController@createEmail');
Route::post('/test-email-send','TestEmailJobController@sendEmail')->name('send.email');

app\Http\Controllers\TestEmailJobController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Mail;
use App\Jobs\TestEmailJob;
use App\Mail\TestEmail;
use App\Product;
use App\User;

class TestEmailJobController extends Controller
{
    public function createEmail(){
        return view('EmailTest.create');
    }

    public function sendEmail(Request $request){
        $product = new Product();
        $product->name = $request->name;
        $product->description = $request->description;
        $product->save();

        $users = User::all();
        foreach($users as $user){
            dispatch(new TestEmailJob($user,$product));
        }
        return redirect()->back();
    }
}

Create a Product add blade file

resources\views\EmailTest\create.blade.php

create product and send email to all users
<!DOCTYPE html>
<html lang="en">
   <head>
      <title>Queue jobs</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
   </head>
   <body>
      <div class="container">
        <br>
         <h3>Send mail to multiple users using Queue in Laravel 8.</h3>
         <br>
         <br>
         <div class="card">
            <form method="post" action="{{route('send.email')}}">
               @csrf
               <div class="card-header">Please fill up all the Field's.</div>
               <div class="card-body">
                  <div class="row">
                     <div class="col-md-6">
                        <label for="Name">Product Name :</label>
                        <input type="text" class="form-control" name="name" required>
                     </div>
                     <div class="col-md-6">
                        <label for="description">Description  :</label>
                        <input type="text" class="form-control"  name="description" required>
                     </div>
               </div>
               </div>
               <div class="col-md-3">
                  <button type="submit" class="btn btn-block btn-info btn-sm">Save</button>
               </div>
          </div>
         </form>
      </div>
   </body>
</html>

Create a Job

php artisan make:job TestEmailJob

app\jobs\TestEmailJob.php

<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Mail\TestEmail;
use Mail;

class TestEmailJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;


    /**
     * Create a new job instance.
     *
     * @return void
     */
    protected $user;
    protected $product;

    public function __construct($user,$product)
    {
        $this->user = $user;
        $this->product = $product;
    }
    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $email = new TestEmail($this->user,$this->product);
        Mail::to($this->user['email'])->send($email);
    }
}

Create a Mail

php artisan make:mail TestEmail

app\Mail\Test\TestEmail.php

<?php

namespace App\Mail;

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

class TestEmail extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public $user;
    public $product;

    public function __construct($user,$product)
    {

        $this->user = $user;
        $this->product = $product;
    }
    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->view('emails.testMailJob');
    }
}

Create a Mail Blade file

resources\views\emails\testMailJob.blade.php

<body>
<h1>Hello</h1>
{{ $user['name'] }}
{{ $user['email'] }}
<p>How are you ?</p>
<p>Your favorite product {{ $product['name'] }} is Available now.
</body>

Start Queue to send Email

Go to the database and see the jobs table. There is one entry for the job. So that means the process of that job is not started. So Laravel, there is a concept called Queue Worker. So we need to run that Queue Worker.

Switch to the new terminal and type the following command to start the queue worker.

php artisan queue:listen
queue listen in terminal to start queue jobs

Run application Server :

127.0.0.1:8000/test-email-create
php artisan queue:listen

Output :

add product to send email to all users

product store in products table

start queue jobs terminal to send emails in laravel

mailtrap inbox eith emails

email from mailtrap

mailtrap testing server

Note: If you getting any error and exception to send emails, you can see these errors on failed_jobs table.

queue failed exception
queue failed errors in exception column in failed_jobs table

In this article, we learned  How to send email to multiple users using Queue in Laravel and queue jobs in laravel example”, I hope this article will help you with your Laravel application Project.

Read also : Password Reset in Laravel using Gmail.

Hi, My name is Gaurav Pandey. I'm a Laravel developer, owner of 8Bityard. I live in Uttarakhand - India and I love to write tutorials and tips that can help other developers. I am a big fan of PHP, Javascript, JQuery, Laravel, WordPress. connect@8bityard.com