How to Send Email to Multiple Users in Laravel?

By Hardik Savani January 29, 2022 Category : Laravel

Hello Dev,

In this example, you will learn how to send emails to multiple users in laravel. We will look at an example of laravel send email to multiple users. We will use laravel send email to all users. This tutorial will give you a simple example of laravel send mail to multiple recipients from database.

Today, i will give you step by step tutorial on how to send emails to selected multiple users in laravel. you can use this example with laravel 6, laravel 7, laravel 8 and laravel 9 version.

You can see bellow preview of example and follow bellow step to sending mail to multiple users in laravel app.

Preview:

Let's follow following steps:

Step 1: Install Laravel

This step is not required; however, if you have not created the laravel app, then you may go ahead and execute the below command:

composer create-project --prefer-dist laravel/laravel blog

Step 2: Make Mail Configuration

This step is require. you must have to setup sender email configuration with driver, host, post, username and email etc. so let's add following configuration in .env file.

.env

MAIL_DRIVER=smtp

MAIL_HOST=smtp.gmail.com

MAIL_PORT=587

MAIL_USERNAME=mygoogle@gmail.com

MAIL_PASSWORD=rrnnucvnqlbsl

MAIL_ENCRYPTION=tls

MAIL_FROM_ADDRESS=mygoogle@gmail.com

MAIL_FROM_NAME="${APP_NAME}"

Step 3: Create Mail Class

Next, we will simply create UserEmail mail class by using laravel artisan command and then we will define view and subject. so let's create mail by bellow command and put code on UserEmail.php file.

php artisan make:mail UserEmail

app/Mail/UserEmail.php

<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;

use Illuminate\Contracts\Queue\ShouldQueue;

use Illuminate\Mail\Mailable;

use Illuminate\Queue\SerializesModels;

class UserEmail extends Mailable

{

use Queueable, SerializesModels;

public $user;

/**

* Create a new message instance.

*

* @return void

*/

public function __construct($user)

{

$this->user = $user;

}

/**

* Build the message.

*

* @return $this

*/

public function build()

{

return $this->subject('Mail from ItSolutionStuff.com')

->view('emails.userEmail');

}

}

Next, we will create email blade file call userEmail in emails folder with bellow code. so just updated userEmail.blade.php file.

resources/views/emails/userEmail.blade.php

<!DOCTYPE html>

<html>

<head>

<title>ItsolutionStuff.com</title>

</head>

<body>

<h1>Hi, {{ $user->name }}</h1>

<p>{{ $user->email }}</p>

<p>Thank you</p>

</body>

</html>

Step 4: Add Routes

Furthermore, open routes/web.php file and add the routes to manage GET and POST requests for list of users and send email method.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\UserController;

/*

|--------------------------------------------------------------------------

| 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('users', [UserController::class, 'index'])->name('users.index');

Route::post('users-send-email', [UserController::class, 'sendEmail'])->name('ajax.send.email');

Step 5: Create Controller

In this step, we will create a new UserController; in this file, we will add the logic to fetch records from the database and pass it to the view file and send email.

So, let's update following code to Controller File.

app\Http\Controllers\UserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

use App\Mail\UserEmail;

use Mail;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index(Request $request)

{

$users = User::select("*")

->paginate(10);

return view('users', compact('users'));

}

/**

* Write code on Method

*

* @return response()

*/

public function sendEmail(Request $request)

{

$users = User::whereIn("id", $request->ids)->get();

foreach ($users as $key => $user) {

Mail::to($user->email)->send(new UserEmail($user));

}

return response()->json(['success'=>'Send email successfully.']);

}

}

you can also send email to multiple recipients from database at once. as bellow optional code. you can view it as well.

/**

* Write code on Method

*

* @return response()

*/

public function sendEmail(Request $request)

{

$users = User::whereIn("id", $request->ids)->get();

Mail::to($users)->send(new UserEmail());

return response()->json(['success'=>'Send email successfully.']);

}

Step 6: Create Blade View

In this step, we will simply create users.blade file and update bellow code:

resources/views/users.blade.php

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>Laravel Send Email to Multiple Users - ItSolutionStuff.com</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<meta name="csrf-token" content="{{ csrf_token() }}" />

</head>

<body>

<div class="container">

<h1>Laravel Send Email to Multiple Users - ItSolutionStuff.com</h1>

<button class="btn btn-success send-email">Send Email</button>

<table class="table table-bordered data-table">

<thead>

<tr>

<th>#</th>

<th>No</th>

<th>Name</th>

<th>Email</th>

</tr>

</thead>

<tbody>

@foreach($users as $user)

<tr>

<td><input type="checkbox" class="user-checkbox" name="users[]" value="{{ $user->id }}"></td>

<td>{{ $user->id }}</td>

<td>{{ $user->name }}</td>

<td>{{ $user->email }}</td>

</tr>

@endforeach

</tbody>

</table>

{{ $users->links() }}

</div>

<script type="text/javascript">

$.ajaxSetup({

headers: {

'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')

}

});

$(".send-email").click(function(){

var selectRowsCount = $("input[class='user-checkbox']:checked").length;

if (selectRowsCount > 0) {

var ids = $.map($("input[class='user-checkbox']:checked"), function(c){return c.value; });

$.ajax({

type:'POST',

url:"{{ route('ajax.send.email') }}",

data:{ids:ids},

success:function(data){

alert(data.success);

}

});

}else{

alert("Please select at least one user from list.");

}

console.log(selectRowsCount);

});

</script>

</body>

</html>

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/users

you will see bellow output:

i hope it can help you...

Tags :