Yasser CHENIK
Yasser CHENIK

Reputation: 407

Capture new Email event in PHP-IMAP in laravel

I want to fetch all emails in inbox and store them in realtime but the way i m doing it is a little bit wrong : it's something like this:

class Kernel extends ConsoleKernel
 ...
   
$schedule->call(function () {

// connect using credentials

//get all emails

//copy emails

//delete emails when they get copied correctly
  
})->everyMinute(); // repeat

this Guarantees that the emails in the database will not be copied because the emails are no longer in the inbox . But now we have a case where we need to keep these messages so we replaced this with :


// connect using credentials

//get all emails 

//filter only unseen

//copy emails

//mark these emails as seen

But the problem of all of these solution is that we get emails . The solution we did is working but added another problem of reloading same emails over and over .

I reread the Documentation and found this possible solution : Using events that triggers in the entire package and capture the new event witch gets triggered when a new email is received. In this example i found some useful methods and classes .

class CustomMessageNewEvent extends Webklex\PHPIMAP\Events\MessageNewEvent {

    /**
     * Create a new event instance.
     * @var \Webklex\PHPIMAP\Message[] $messages
     * @return void
     */
    public function __construct($messages) {
        $this->message = $messages[0];
        echo "New message: ".$this->message->subject."\n";
    }
}


But i m not sure how to implement them in Laravel , juste where and how should i register / capture this `new` Event !
**Especially that we have multiple Client instances not only one ( foreach user ... )**
Thank you so much for reading all this and hopefully people find this question useful.

Upvotes: 0

Views: 970

Answers (1)

Joundill
Joundill

Reputation: 7533

When I've done similar tasks in the past I've used the Message-ID defined in the email spec to identify each email uniquely.

You can use your IMAP library to get a list of emails with their Message-IDs, then compare those Message-IDs to your database. Just make sure you add a new field to your Email model (or whatever you've called it) to store the Message-ID.

Upvotes: 0

Related Questions