How to mail receiving time and date in laravel php

In Laravel, you can get the current date and time when a mail is received using the now() function provided by the Carbon library. Here are a few ways to achieve this:

Method 1: Using the now() function in the mail's handle method

You can override the handle method in your mail class to capture the current date and time when the mail is received. Here's an example:

namespace App\Mail;

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

class MyMail extends Mailable
{
    use Queueable, SerializesModels;

    public function handle()
    {
        $currentTime = now();
        // Do something with the current time
        return $this->markdown('emails.my-mail');
    }
}

In this example, the handle method is called when the mail is received, and the now() function returns the current date and time.

Method 2: Using the now() function in a middleware

You can create a middleware that captures the current date and time when the mail is received. Here's an example:

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Mail;

class MailReceivedTime
{
    public function handle(Request $request, Closure $next)
    {
        $currentTime = now();
        // Do something with the current time
        return $next($request);
    }
}

Then, in your kernel.php file, add the middleware to the mail middleware group:

protected $middlewareGroups = [
    'web' => [
        //...
    ],
    'mail' => [
        \App\Http\Middleware\MailReceivedTime::class,
    ],
];

Method 3: Using the now() function in a custom mail listener

You can create a custom mail listener that captures the current date and time when the mail is received. Here's an example:

namespace App\Listeners;

use Illuminate\Mail\Events\MessageSent;
use Illuminate\Support\Facades\Log;

class MailReceivedTime
{
    public function handle(MessageSent $event)
    {
        $currentTime = now();
        // Do something with the current time
        Log::info("Mail received at: $currentTime");
    }
}

Then, in your kernel.php file, add the listener to the mail listener group:

protected $listen = [
    'Illuminate\Mail\Events\MessageSent' => [
        \App\Listeners\MailReceivedTime::class,
    ],
];

In all these examples, the now() function returns the current date and time in the format YYYY-MM-DD HH:MM:SS. You can format the date and time as needed using the Carbon library.