Sample code for 30+ languages & platforms
PowerShell

Search an IMAP Mailbox

See more IMAP Examples

Demonstrates the Chilkat Imap.QueryMbx method, which searches the selected mailbox using IMAP search criteria and stores the matching message identifiers in a MessageSet. If bUid is true, the identifiers are UIDs; otherwise they are sequence numbers. This example finds unseen messages and lists their UIDs.

Background: IMAP search runs on the server, so you can find matching messages without downloading them. The criteria string is standard IMAP search syntax — for example UNSEEN, FROM "alice@example.com", SUBJECT "invoice", or SINCE 1-Jan-2026 — and terms can be combined. The result is a MessageSet of identifiers you then fetch, flag, copy, or move. Requesting UIDs (bUid = true) is preferred because UIDs remain valid across sessions.

Chilkat PowerShell Downloads

PowerShell
Add-Type -Path "C:\chilkat\ChilkatDotNet47-x64\ChilkatDotNet47.dll"

$success = $false

#  Demonstrates the Imap.QueryMbx method, which searches the selected mailbox using IMAP
#  search criteria and stores the matching message identifiers in a MessageSet.  If bUid is
#  $true, the identifiers are UIDs; otherwise they are sequence numbers.

$imap = New-Object Chilkat.Imap

$imap.Ssl = $true
$imap.Port = 993

$success = $imap.Connect("imap.example.com")
if ($success -eq $false) {
    $($imap.LastErrorText)
    exit
}

$success = $imap.Login("user@example.com","myPassword")
if ($success -eq $false) {
    $($imap.LastErrorText)
    exit
}

$success = $imap.SelectMailbox("Inbox")
if ($success -eq $false) {
    $($imap.LastErrorText)
    exit
}

#  Search for unseen (unread) messages, returning their UIDs.
$msgSet = New-Object Chilkat.MessageSet
$success = $imap.QueryMbx("UNSEEN",$true,$msgSet)
if ($success -eq $false) {
    $($imap.LastErrorText)
    exit
}

#  Iterate the matching message identifiers.
$n = $msgSet.Count
$("Matching messages: " + $n)

for ($i = 0; $i -le $n - 1; $i++) {
    $("UID: " + $msgSet.GetId($i))
}

$success = $imap.Disconnect()
if ($success -eq $false) {
    $($imap.LastErrorText)
    exit
}