Sample code for 30+ languages & platforms
Tcl Requires Chilkat v11.0.0+

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 Tcl Downloads

Tcl

load ./chilkat.dll

set success 0

#  Assumes Chilkat is unlocked. See Global Unlock Sample.

set oauth [new_CkOAuth2]

CkOAuth2_put_TokenEndpoint $oauth "https://login.microsoftonline.com/common/oauth2/v2.0/token"
CkOAuth2_put_ClientId $oauth "CLIENT_ID"
#  A public desktop client does not have a client secret.

CkOAuth2_put_AuthorizationEndpoint $oauth "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"
CkOAuth2_put_LocalHost $oauth "localhost"
CkOAuth2_put_ListenPort $oauth 3017
CkOAuth2_put_CodeChallenge $oauth 1
CkOAuth2_put_CodeChallengeMethod $oauth "S256"
#  Request only the protocols your application needs; this sample covers all three.
CkOAuth2_put_Scope $oauth "offline_access https://outlook.office.com/SMTP.Send https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/POP.AccessAsUser.All"
set success [CkOAuth2_AddAuthQueryParam $oauth "prompt" "select_account"]
if {$success != 1} then {
    puts "Could not configure account selection."
    delete_CkOAuth2 $oauth
    exit
}

set authUrl [CkOAuth2_startAuth $oauth]
if {[CkOAuth2_get_LastMethodSuccess $oauth] != 1} then {
    puts "Could not start the loopback listener."
    delete_CkOAuth2 $oauth
    exit
}

set success [CkOAuth2_LaunchBrowser $oauth $authUrl]
if {$success != 1} then {
    CkOAuth2_Cancel $oauth
    puts "Could not open the system browser."
    delete_CkOAuth2 $oauth
    exit
}

set waited 0
while {expr [[CkOAuth2_get_AuthFlowState $oauth] < 3]  &&  [$waited < 180000]} {
    CkOAuth2_SleepMs $oauth 200
    set waited [expr $waited + 200]
}
if {[CkOAuth2_get_AuthFlowState $oauth] < 3} then {
    CkOAuth2_Cancel $oauth
    puts "Authorization timed out."
    delete_CkOAuth2 $oauth
    exit
}

if {[CkOAuth2_get_AuthFlowState $oauth] != 3} then {
    puts "Authorization did not complete. Flow state: [CkOAuth2_get_AuthFlowState $oauth]"
    delete_CkOAuth2 $oauth
    exit
}

set token [new_CkJsonObject]

set success [CkJsonObject_Load $token [CkOAuth2_accessTokenResponse $oauth]]
if {$success != 1} then {
    puts "Could not parse the token response."
    delete_CkOAuth2 $oauth
    delete_CkJsonObject $token
    exit
}

if {expr [[CkJsonObject_JsonTypeOf $token "refresh_token"] != 1]  ||  [[CkJsonObject_StringOfEquals $token "refresh_token" "" 1] == 1]} then {
    puts "No offline refresh token was issued. The existing cache was preserved."
    delete_CkOAuth2 $oauth
    delete_CkJsonObject $token
    exit
}

if {expr [[CkJsonObject_JsonTypeOf $token "access_token"] != 1]  ||  [[CkJsonObject_StringOfEquals $token "access_token" "" 1] == 1]} then {
    puts "The response did not contain an access token. The existing cache was preserved."
    delete_CkOAuth2 $oauth
    delete_CkJsonObject $token
    exit
}

set obtained [new_CkDateTime]

CkDateTime_SetFromCurrentSystemTime $obtained
CkJsonObject_UpdateString $token "obtained_at" [CkDateTime_getAsTimestamp $obtained 0]
#  The token response includes expires_in (seconds). Refresh before the access token expires.
#  The file contains credentials: use a private, access-controlled directory.
set success [CkJsonObject_WriteFile $token "qa_data/tokens/office365.json"]
if {$success != 1} then {
    puts "Could not save the token file."
    delete_CkOAuth2 $oauth
    delete_CkJsonObject $token
    delete_CkDateTime $obtained
    exit
}

puts "Credentials saved in the private working directory."

delete_CkOAuth2 $oauth
delete_CkJsonObject $token
delete_CkDateTime $obtained