This tutorial will guide you through the process of sending 1000 emails with the help of queues in Laravel 10. This includes creating a users table, inserting 1000 email addresses, and executing email-sending tasks asynchronously using Laravel queues.
Create mailtrap account free and use Click To view Blog
composer create-project --prefer-dist laravel/laravel queue-email-demo
In the .env
file, configure your database and mail settings:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_db
DB_USERNAME=root
DB_PASSWORD=
MAIL_MAILER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=your_mailtrap_username
MAIL_PASSWORD=your_mailtrap_password
MAIL_ENCRYPTION=null
php artisan make:migration create_users_table
Update the migration file to create the users table:
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamps();
});
Insert the following code in DatabaseSeeder.php
to seed users:
use App\Models\User;
use Faker\Factory as Faker;
public function run() {
$faker = Faker::create();
for ($i = 0; $i < 1000; $i++) {
User::create([
'name' => $faker->name,
'email' => $faker->email,
]);
}
}
php artisan db:seed
php artisan make:mail UserMail
Modify the UserMail
class:
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
class UserMail extends Mailable {
use Queueable, SerializesModels;
public $user;
public function __construct($user) {
$this->user = $user;
}
public function build() {
return $this->view('emails.user')->with([
'userName' => $this->user->name,
]);
}
}
php artisan make:job SendEmailJob
Update the SendEmailJob
class:
use App\Mail\UserMail;
use Illuminate\Bus\Queueable;
use Illuminate\Support\Facades\Mail;
class SendEmailJob implements ShouldQueue {
use Queueable;
public $user;
public function __construct($user) {
$this->user = $user;
}
public function handle() {
Mail::to($this->user->email)->send(new UserMail($this->user));
}
}
use App\Jobs\SendEmailJob;
use App\Models\User;
public function sendEmails() {
$users = User::all();
foreach ($users as $user) {
SendEmailJob::dispatch($user);
}
return response()->json(['message' => 'Emails are being sent!']);
}
php artisan queue:work
<!DOCTYPE html>
<html>
<head>
<title>Email Notification</title>
</head>
<body>
<h1>Hello, {{ $userName }}</h1>
<p>This is a test email sent via Laravel Queues!</p>
</body>
</html>
Route::get('/send-emails', 'App\Http\Controllers\EmailController@sendEmails');
Visit https://localhost:8000/send-emails
to start sending emails via the queue.
With Laravel queues, you can efficiently send 1000 emails asynchronously, ensuring a seamless user experience. Implement queues in your projects to handle heavy tasks in the background!