Microsoft 365 IMAP: OAuth2 Login and Read-Only Inbox
See more IMAP Examples
Authenticate to outlook.office365.com:993 using XOAUTH2, then EXAMINE the Inbox without changing read flags. This is Exchange Online work/school access: the mailbox must permit IMAP and the app must satisfy tenant consent and access policy. Basic authentication and app passwords cannot restore removed IMAP Basic authentication.
Personal Outlook.com uses the same IMAP server, but requires personal-account delegated authorization and IMAP enabled in Outlook.com settings. To use it here, select that mailbox address and load qa_data/tokens/hotmail.json from the personal-account PKCE example. Application-only client credentials are an Exchange Online organizational scenario, not personal Outlook.com authorization.
First authorize the account with https://outlook.office.com/IMAP.AccessAsUser.All and offline_access, then refresh the access token when needed. This example reads qa_data/tokens/office365.json from a private working directory. Microsoft Graph permissions such as Mail.Send or Mail.Read do not authorize these mail protocols. Do not print tokens or authentication logs.
Microsoft reference documentation
Chilkat AutoIt Downloads
Local $bSuccess = False
; Assumes Chilkat is unlocked. See Global Unlock Sample.
$oToken = ObjCreate("Chilkat.JsonObject")
$bSuccess = $oToken.LoadFile("qa_data/tokens/office365.json")
If ($bSuccess <> True) Then
ConsoleWrite("Could not read qa_data/tokens/office365.json from the private working directory." & @CRLF)
Exit
EndIf
If (($oToken.JsonTypeOf("access_token") <> 1) Or ($oToken.StringOfEquals("access_token","",True) = True)) Then
ConsoleWrite("An OAuth access token is required. Authorize or refresh the account first." & @CRLF)
Exit
EndIf
Local $sMailbox = "user@example.com"
$oImap = ObjCreate("Chilkat.Imap")
$oImap.Ssl = True
$oImap.Port = 993
$oImap.RequireSslCertVerify = True
$oImap.AuthMethod = "XOAUTH2"
$bSuccess = $oImap.Connect("outlook.office365.com")
If ($bSuccess <> True) Then
ConsoleWrite("Could not establish the Microsoft IMAP TLS connection." & @CRLF)
Exit
EndIf
$bSuccess = $oImap.Login($sMailbox,$oToken.StringOf("access_token"))
If ($bSuccess <> True) Then
$oImap.Disconnect()
ConsoleWrite("IMAP authentication failed. Check the mailbox, token scope, expiry, and account policy." & @CRLF)
Exit
EndIf
; EXAMINE is read-only; no message is downloaded, marked read, moved, or deleted.
$bSuccess = $oImap.ExamineMailbox("INBOX")
If ($bSuccess <> True) Then
$oImap.Logout()
$oImap.Disconnect()
ConsoleWrite("Could not examine INBOX." & @CRLF)
Exit
EndIf
ConsoleWrite("Messages in INBOX: " & $oImap.NumMessages & @CRLF)
$bSuccess = $oImap.Logout()
$oImap.Disconnect()
If ($bSuccess <> True) Then
ConsoleWrite("The read-only operation completed, but IMAP logout failed." & @CRLF)
EndIf