PowerShell Requires Chilkat v11.0.0+
PowerShell
Find an email by subject and fetch it by IMAP UID
See more Email Object Examples
Search the selected INBOX by subject and fetch the first matching UID into an Email. The example requests complete attachment bodies and uses peek mode to preserve the read flag. Configure your own IMAP TLS endpoint and credentials.
Chilkat PowerShell Downloads
Add-Type -Path "C:\chilkat\ChilkatDotNet47-x64\ChilkatDotNet47.dll"
$success = $false
# Assumes Chilkat is unlocked. See Global Unlock Sample.
$imap = New-Object Chilkat.Imap
$imap.Ssl = $true
$imap.Port = 993
$imap.RequireSslCertVerify = $true
$imap.PeekMode = $true
$imap.AutoDownloadAttachments = $true
$success = $imap.Connect("imap.example.com")
if ($success -ne $true) {
$($imap.LastErrorText)
exit
}
$success = $imap.Login("MAIL_USER","MAIL_PASSWORD")
if ($success -ne $true) {
$($imap.LastErrorText)
exit
}
$success = $imap.SelectMailbox("INBOX")
if ($success -ne $true) {
$($imap.LastErrorText)
exit
}
$matches = New-Object Chilkat.MessageSet
$success = $imap.QueryMbx("SUBJECT `"Sample message`"",$true,$matches)
if ($success -ne $true) {
$($imap.LastErrorText)
exit
}
if ($matches.Count -eq 0) {
$("No matching message in INBOX.")
$success = $imap.Disconnect()
if ($success -ne $true) {
$($imap.LastErrorText)
exit
}
exit
}
# The search returned UIDs. Use the same identifier type for the fetch.
$uid = $matches.GetId(0)
$email = New-Object Chilkat.Email
$success = $imap.FetchEmail($false,$uid,$true,$email)
if ($success -ne $true) {
$($imap.LastErrorText)
exit
}
$("Mailbox INBOX, UIDVALIDITY " + $imap.UidValidity + ", UID " + $uid)
$success = $imap.Disconnect()
if ($success -ne $true) {
$($imap.LastErrorText)
exit
}
# The downloaded Email remains usable after disconnecting.
$("Subject: " + $email.Subject + " Files: " + $email.NumAttachments)
$success = $email.SaveEml("imap-received.eml")
if ($success -ne $true) {
$($email.LastErrorText)
exit
}
$("Saved imap-received.eml.")