How To Send Bulk Email Using Laravel

Hey there, If you are building something interesting and looking to send bulk emails using your application’s in-built power provided by Laravel itself. You can do that easily.

You can use SMTP or external services like Mailgun or Sendgrid as well.

In this blog, I’ll walk through the process step-by-step, and I’ll provide example code snippets along the way.

Prerequisites

Installation

Make sure you have a laravel application up and running.

composer create-project --prefer-dist laravel/laravel bulk_email_app
cd bulk_email_app

Configure Mail Credentials

Now you have to go to your .env file and add your email credentials.

MAIL_MAILER=smtp
MAIL_HOST=mailpit
MAIL_PORT=1025
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_ENCRYPTION=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"

Seeder

In my case, I have seeded a few emails to perform the bulk email action. But in your case, you may be uploading via CSV or you may be just entering them in the tables manually. But at the end when we have emails in the db the case is the same to send them.

I’ll be using Mailtrap for email testing.

Set Up the Queue Driver

Mostly we use database the driver. You can configure it in your .env file:

QUEUE_CONNECTION=database

Create An Artisan Command

Create an Artisan command that will dispatch a job to send the bulk emails. Run the following command to create the job:

php artisan make:command SendBulkEmails

In the SendBulkEmails command, dispatch a job to send the emails:

<?php

namespace App\Console\Commands;

use App\Jobs\SendBulkEmailJob;
use App\Models\User;
use Illuminate\Console\Command;

class SendBulkEmails extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:send-bulk-emails';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $users= User::query()->select('email')->get();
        $data['emails'] = $users;
        $data['subject'] = 'Newsletter Email';
        $data['content'] = 'This is newsletter email';
        SendBulkEmailJob::dispatch($data);
    }
}

Create Mail

I have created a mail called NewletterEMail which we will represent a particular mail template. In view you can pass your view template/blade file.

//app/Mail/NewsletterEmail.php

<?php

namespace App\Mail;

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

class NewsletterEmail extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     */
    public function __construct(
        public string $content,
        public $subject
    )
    {

    }

    /**
     * Get the message envelope.
     */
    public function envelope(): Envelope
    {
        return new Envelope(
            subject: $this->subject,
        );
    }

    /**
     * Get the message content definition.
     */
    public function content(): Content
    {
        return new Content(
            view: 'mail'
        );
    }

    /**
     * Get the attachments for the message.
     *
     * @return array<int, \Illuminate\Mail\Mailables\Attachment>
     */
    public function attachments(): array
    {
        return [];
    }
}

Create a Job for Sending Bulk Emails

We have to create a job to send bulk emails.

php artisan make:job SendBulkEmailJob
<?php

namespace App\Jobs;

use App\Mail\NewsletterEmail;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Mail;

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

    /**
     * Create a new job instance.
     */
    public function __construct(
        protected  array $data
    )
    {
        $this->data = $data;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        $emailContent = $this->data['content'];
        $subject = $this->data['subject'];
        $emailList = $this->data['emails'];

        foreach ($emailList as $email) {
            Mail::to($email->email)->send(new NewsletterEmail($emailContent, $subject));
        }
    }
}

Migrate Job Table

// it will generate table for queued jobs
php artisan queue:table

// migrate
php artisan migrate

Schedule the Email Sending Task

Now, let’s set up the Laravel scheduler to run the email-sending task periodically. Edit the app/Console/Kernel.php file and add the following code to the schedule method:

// app/Console/Kernel.php

use App\Console\Commands\SendBulkEmails;


    protected function schedule(Schedule $schedule): void
    {
        // $schedule->command('inspire')->hourly();
        $schedule->command('app:send-bulk-emails')->dailyAt('16:41');
    }

Perform

Now, you can run the below command to test the whole process.

php artisan queue:listen

That’s it! You have set up a scheduled task to send bulk emails in the background using Laravel’s task scheduling and the queue system. Make sure to customize the code and configuration according to your specific needs and requirements.

Related:

  1. Sending Mails Using PHP With Mail Function
  2. Queue Emails In Laravel | Save Load Time
  3. Send Email With Attachment In Laravel (Laravel 8)
  4. How to send mail in Laravel with a template

Leave a Comment