$outlook = New-Object -ComObject Outlook.Application $namespace = $outlook.GetNamespace("MAPI") # Target mailbox $mailboxName = "svc_huloop@qnbtrust.bank" $mailbox = $null for ($i = 1; $i -le $namespace.Folders.Count; $i++) { if ($namespace.Folders.Item($i).Name -eq $mailboxName) { $mailbox = $namespace.Folders.Item($i) break } } if (-not $mailbox) { Write-Output "MAILBOX_NOT_FOUND" exit } # Inbox + restrict to unread $inbox = $mailbox.Folders.Item("Inbox") $items = $inbox.Items $items.Sort("[ReceivedTime]", $false) $unreadItems = $items.Restrict("[UnRead] = true") # Settings $subjectMatch = "Admin Platform" $codeRegex = [regex]"Access Code is[:\s]+(\d{5,6})" $cutoff = (Get-Date).AddMinutes(-10) # Scan unread items within time window foreach ($item in $unreadItems) { if ($item -ne $null -and $item.Class -eq 43) { $received = $item.ReceivedTime if ($received -lt $cutoff) { continue } if ($item.Subject -like "*$subjectMatch*") { $body = $item.Body if ($body) { $match = $codeRegex.Match($body) if ($match.Success) { Write-Output $match.Groups[1].Value exit } } } } } Write-Output "CODE_NOT_FOUND"