T
T
tesko2021-06-17 04:35:56
PHP
tesko, 2021-06-17 04:35:56

How to optimize the receipt of IMAP emails?

There is a task - to find a letter with a link, bypassing all mail folders, tk. it can fall into spam, and into the inbox, or somewhere else. I'm using the PHP IMAP

library . The problem is that sometimes it takes a very long time to find an email. Most likely because of array_reduce, but I don’t know how else to do it. Please tell me the best way to solve my problem. Here is a piece of code




// Additional search parameters
$searchParams = [
    'FROM'    => getPostField('from'),
    'TO'      => getPostField('to'),
    'SUBJECT' => getPostField('subject'),
    'BODY'    => getPostField('body'),
];

$mailbox = connect($host, $port, $login, $password, $type, $ssl);

// get the list of folders/mailboxes
$folders = $mailbox->getMailboxes();

$mails_ids = array_reduce($folders, function ($sum, $folder) use ($mailbox, $searchParams) {
    // switch to particular mailbox
    $mailbox->switchMailbox($folder['fullpath']);

    $ids = $mailbox->searchMailbox(getSearch($searchParams));

    if ($ids) {
        $sum[$folder['fullpath']] = $ids;
    }
    return $sum;
}, []);

if (empty($mails_ids)) {
    exit(json_encode(['status' => 'mails not found']));
}

$emails = [];

foreach($mails_ids as $folder => $mail_folder_ids) {
    $mailbox->switchMailbox($folder);

    foreach ($mail_folder_ids as $mail_id) {
        $email = $mailbox->getMail($mail_id);

        $mailbox->markMailAsRead($mail_id);
        $emails[$email->date] = $email;
    }
}

krsort($emails);
$email = array_shift($emails);

$pattern = '~[a-z]+://[^"]+~';
preg_match_all($pattern, $email->textHtml, $matches);
echo json_encode($matches[0]);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Edward, 2021-06-17
@Drayde

https://www.php.net/manual/en/function.imap-search.php

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question