Sure.
First, as mentioned before this is not SMTP, so all the SMTP_* constants you are using are either the wrong values or incorrectly named. Either make new IMAP settings to use or rename your constants.
Second, this is based on some code I have that checks an email account for a one-time-password code so I can login and download data from a site.
<?php
//Example parameters.
$host = '{imap.example.com:993/ssl/readonly}';
$mailbox = '
[email protected]';
$password = '';
function getSecurityCode(string $host, string $mailbox, string $password) : ?string{
$authCode = null;
$startTime = time();
do {
sleep(5);
$handle = imap_open($host, $mailbox, $password, OP_READONLY, 5);
if (!$handle){
throw new RuntimeException('Unable to open mailbox');
}
$messageList = imap_sort($handle, SORTDATE, 1);
foreach ($messageList as $messageNumber){
$messageInfo = imap_fetch_overview($handle, $messageNumber)[0];
if (isOTPEmail($messageInfo) && isReceivedInLast5Minutes($messageInfo)){
$authCode = extractAuthCode(imap_body($handle, $messageNumber));
break;
}
}
imap_close($handle);
} while (!$authCode && time() - $startTime < 300);
return $authCode;
}
function isOTPEmail(stdClass $messageInfo) : bool{
if (!isset($messageInfo->subject)){
return false;
}
return stripos($messageInfo->from, '
[email protected]') !== false
&& stripos($messageInfo->subject, 'One-Time Passcode') !== false;
}
function isReceivedInLast5Minutes(stdClass $messageInfo) : bool{
if (!isset($messageInfo->date)){
return false;
}
$date = DateTime::createFromFormat(DateTimeInterface::RFC2822, $messageInfo->date);
if ($date === false){
$date = DateTime::createFromFormat(DateTimeInterface::RFC2822 . ' (\G\M\T)', $messageInfo->date);
}
if ($date === false){
return false;
}
$now = new DateTime('', $date->getTimezone());
$now->sub(new DateInterval('PT5M'));
return $date > $now;
}