Microsoft 365: Obtain Mail OAuth2 Tokens with Desktop PKCE
See more Office365 Examples
Obtain delegated SMTP, IMAP, and POP access with authorization code flow and S256 PKCE. Register a public desktop application in Microsoft Entra with a Mobile and desktop applications loopback redirect URI of http://localhost:3017/. Do not register this callback as a Web or SPA application. No client secret belongs in a distributed desktop application. Run the sample where the user can launch a browser and return to the local listener; it is not a web-server callback example.
The common authority supports work/school and personal accounts only if the app registration supports those account types. For a single-tenant work/school app, replace common in both endpoints with the mailbox tenant ID. The account needs an Exchange Online mailbox; administrator consent or Conditional Access can restrict authorization.
The example requests all three delegated protocol permissions for demonstration. Remove unused scopes in your application. Microsoft Graph scopes and ID tokens are not substitutes for mail-protocol access tokens. The user may need consent again after revocation or policy changes; refresh is not guaranteed indefinitely.
Create qa_data/tokens in a private, access-controlled working directory before running. The saved JSON contains credentials, not just settings. Use separate caches per account, app, and authority; prevent concurrent writers, use an OS credential store in production, and never publish token responses. The sample validates the response before writing, but a production cache also needs atomic replacement and recovery from write failures.
Microsoft reference documentation
Chilkat AutoIt Downloads
Local $bSuccess = False
; Assumes Chilkat is unlocked. See Global Unlock Sample.
$oOauth = ObjCreate("Chilkat.OAuth2")
$oOauth.TokenEndpoint = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
$oOauth.ClientId = "CLIENT_ID"
; A public desktop client does not have a client secret.
$oOauth.AuthorizationEndpoint = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"
$oOauth.LocalHost = "localhost"
$oOauth.ListenPort = 3017
$oOauth.CodeChallenge = True
$oOauth.CodeChallengeMethod = "S256"
; Request only the protocols your application needs; this sample covers all three.
$oOauth.Scope = "offline_access https://outlook.office.com/SMTP.Send https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/POP.AccessAsUser.All"
$bSuccess = $oOauth.AddAuthQueryParam("prompt","select_account")
If ($bSuccess <> True) Then
ConsoleWrite("Could not configure account selection." & @CRLF)
Exit
EndIf
Local $sAuthUrl = $oOauth.StartAuth()
If ($oOauth.LastMethodSuccess <> True) Then
ConsoleWrite("Could not start the loopback listener." & @CRLF)
Exit
EndIf
$bSuccess = $oOauth.LaunchBrowser($sAuthUrl)
If ($bSuccess <> True) Then
$oOauth.Cancel()
ConsoleWrite("Could not open the system browser." & @CRLF)
Exit
EndIf
Local $iWaited = 0
While (($oOauth.AuthFlowState < 3) And ($iWaited < 180000))
$oOauth.SleepMs 200
$iWaited = $iWaited + 200
Wend
If ($oOauth.AuthFlowState < 3) Then
$oOauth.Cancel()
ConsoleWrite("Authorization timed out." & @CRLF)
Exit
EndIf
If ($oOauth.AuthFlowState <> 3) Then
ConsoleWrite("Authorization did not complete. Flow state: " & $oOauth.AuthFlowState & @CRLF)
Exit
EndIf
$oToken = ObjCreate("Chilkat.JsonObject")
$bSuccess = $oToken.Load($oOauth.AccessTokenResponse)
If ($bSuccess <> True) Then
ConsoleWrite("Could not parse the token response." & @CRLF)
Exit
EndIf
If (($oToken.JsonTypeOf("refresh_token") <> 1) Or ($oToken.StringOfEquals("refresh_token","",True) = True)) Then
ConsoleWrite("No offline refresh token was issued. The existing cache was preserved." & @CRLF)
Exit
EndIf
If (($oToken.JsonTypeOf("access_token") <> 1) Or ($oToken.StringOfEquals("access_token","",True) = True)) Then
ConsoleWrite("The response did not contain an access token. The existing cache was preserved." & @CRLF)
Exit
EndIf
$oObtained = ObjCreate("Chilkat.CkDateTime")
$oObtained.SetFromCurrentSystemTime()
$oToken.UpdateString("obtained_at",$oObtained.GetAsTimestamp(False))
; The token response includes expires_in (seconds). Refresh before the access token expires.
; The file contains credentials: use a private, access-controlled directory.
$bSuccess = $oToken.WriteFile("qa_data/tokens/office365.json")
If ($bSuccess <> True) Then
ConsoleWrite("Could not save the token file." & @CRLF)
Exit
EndIf
ConsoleWrite("Credentials saved in the private working directory." & @CRLF)