Home Laravel How to Send Automatic Email in Laravel 9?

How to Send Automatic Email in Laravel 9?

by Shahriar Sagor

Today now in this post i will show you How to Send Automatic Email in Laravel 9? Now in this article goes in detailed about send automatic email laravel 9. Here I would like to share with you laravel 9 auto send email. From here you’ll learn about auto send email laravel 9. Here i will be use laravel 9 send scheduled emails. So let’s get started with laravel 9 send mail automatically.

Now in this example, i will be create an auto send an email for the user birthday wish. So, i will create a “users” table also with a “birthdate” column. Then i will be create one seeder to add some users. So from here you will also know how to use seeder. Then after i will be create one command to send the email that the birthdate match which users today’s date. After the creating the command successfully i will be scheduled daily. So the users will get automatically their birthday wish on email.

So, let’s start and follow the below step to make it done this example:

Step 1: Install Laravel

This step is not needed; however, if we have not created the laravel application, then we may go ahead and execute the below command:

composer create-project laravel/laravel example-app
Step 2: Create Migration

Now here,i will create a new migration for adding the new column birthdate in users table. So let’s run the bellow command:

php artisan make:migration add_birthdate_column

After this command we will be find one new file in following path “database/migrations” and we need to put the bellow code in our migration file for create users table.

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->date('birthdate')->nullable();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        
    }
};

Now you need to run this migration by using following command:

php artisan migrate
Step 3: Update Model

Now in this step, i will add “birthdate” column in the $fillable array.

let’s just copy the below code and paste it.

app/Models/User.php

<?php
  
namespace App\Models;
  
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
  
class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;
    
    /**
     * The attributes that are mass assignable.
     *
     * @var array

     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'birthdate'
    ];
   
    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array

     */
    protected $hidden = [
        'password',
        'remember_token',
    ];
  
    /**
     * The attributes that should be cast.
     *
     * @var array

     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];
}
Step 4: Create Seeder

then in this step i will create the Seeder for adding dummy users. So let’s run the bellow command.

php artisan make:seeder UserSeeder

now, let’s need to update code on UserSeeder.php file as bellow:

database/seeders/UserSeeder.php

<?php
    
namespace Database\Seeders;
  
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use App\Models\User;
  
class UserSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $users = [
            [
                "name" => "sr sagor",
                "email" => "srsagor007@gmail.com",
                "password" => bcrypt("123456"),
                "birthdate" => "1995-05-25"
            ],
            [
                "name" => "shahriar sagor",
                "email" => "sagor@gmail.com",
                "password" => bcrypt("123456"),
                "birthdate" => "1995-06-23"
            ],
            [
                "name" => "sagor shahriar",
                "email" => "shahriar@gmail.com",
                "password" => bcrypt("123456"),
                "birthdate" => "1996-07-23"
            ]
        ];
  
        foreach ($users as $key => $value) {
            User::create($value);
        }
    }
}

Then need to run below seeder to create dummy users.

php artisan db:seed --class=UserSeeder
Step 5: Create Mail Class

Now in this step i will create the mail class BirthDayWish for email send on match date of birth. So let’s need to run bellow command.

php artisan make:mail BirthDayWish

Let’s need to update code on BirthDayWish.php file as like as bellow:

app/Mail/BirthDayWish.php

<?php
  
namespace App\Mail;
  
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
  
class BirthDayWish 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('Happy Birthday '. $this->user->name)
                    ->view('emails.birthdayWish');
    }
}

Here, i will be create blade view file for email. Now in this file i will write the text for birthday wish. Now create bellow files on “emails” folder.

resources/views/emails/birthdayWish.blade.php

<h2>Hey, Happy Birthday {{ $user->name }}</h2> 
<br>
<p>On behalf of the entire company I wish you a very happy birthday and send you my best wishes for much happiness in your life.</p>
    
Thank you

Then , we have to add send mail configuration with the mail driver, mail host, mail port, mail username, mail password .So in laravel will use those sender configuration for sending email. So we can simply add as like as following in env file.

.env

MAIL_MAILER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=mygoogle@gmail.com
MAIL_PASSWORD=rrnnucvnqlbsl
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=mygoogle@gmail.com
MAIL_FROM_NAME="${APP_NAME}"
Step 6: Create Command

Then in this step, i will be create a new command call AutoBirthDayWish. So let’s create the command by using below terminal command:

php artisan make:command AutoBirthDayWish

Now, let’s need to update code on AutoBirthDayWish.php file as bellow:

app/Console/Commands/AutoBirthDayWish.php

<?php
  
namespace App\Console\Commands;
  
use Illuminate\Console\Command;
use Mail;
use App\Mail\BirthDayWish;
use App\Models\User;
  
class AutoBirthDayWish extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'auto:birthdaywith';
  
    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';
  
    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $users = User::whereMonth('birthdate', date('m'))
                    ->whereDay('birthdate', date('d'))
                    ->get();
  
        if ($users->count() > 0) {
            foreach ($users as $user) {
                Mail::to($user)->send(new BirthDayWish($user));
            }
        }
  
        return 0;
    }
}

Next step , i have to scheduled this command daily. So let’s update it in Kernel.php file:

app/Console/Kernel.php

<?php
  
namespace App\Console;
  
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
  
class Kernel extends ConsoleKernel
{
    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        $schedule->command('auto:birthdaywith')->daily();
    }
  
    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__.'/Commands');
  
        require base_path('routes/console.php');
    }
}
Step 7: Cron Job Setup on Server

Here, i will also show you how we can setup cron job command on the server. We have to install crontab on server. if we are using the ubuntu server then it already installed. So let’s run the bellow command and add an ew entry for cron job.

crontab -e

Then , need to add the bellow line to crontab file. So make sure we have to set our project path correctly on it.

* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1

Now, we can check this on server as well.

Read Also: How To Implement Laravel 9 form validation ?

Thanks for read. I hope it help you. For more you can follow us on facebook

close

You may also like