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 Lua Downloads
local chilkat = require("chilkat")
-- Assumes Chilkat is unlocked. See Global Unlock Sample.
local oauth = chilkat.OAuth2.new()
oauth.token_endpoint = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
oauth.client_id = "CLIENT_ID"
-- A public desktop client does not have a client secret.
oauth.authorization_endpoint = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"
oauth.local_host = "localhost"
oauth.listen_port = 3017
oauth.code_challenge = true
oauth.code_challenge_method = "S256"
-- Request only the protocols your application needs; this sample covers all three.
oauth.scope = "offline_access https://outlook.office.com/SMTP.Send https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/POP.AccessAsUser.All"
local success = oauth:add_auth_query_param("prompt", "select_account")
if not success then
print("Could not configure account selection.")
return
end
local authUrl = oauth:start_auth()
if not oauth.last_method_success then
print("Could not start the loopback listener.")
return
end
success = oauth:launch_browser(authUrl)
if not success then
oauth:cancel()
print("Could not open the system browser.")
return
end
local waited = 0
while (oauth.auth_flow_state < 3) and (waited < 180000) do
oauth:sleep_ms(200)
waited = waited + 200
end
if oauth.auth_flow_state < 3 then
oauth:cancel()
print("Authorization timed out.")
return
end
if oauth.auth_flow_state ~= 3 then
print("Authorization did not complete. Flow state: " .. oauth.auth_flow_state)
return
end
local token = chilkat.JsonObject.new()
success = token:load(oauth.access_token_response)
if not success then
print("Could not parse the token response.")
return
end
if (token:json_type_of("refresh_token") ~= 1) or (token:string_of_equals("refresh_token", "", true)) then
print("No offline refresh token was issued. The existing cache was preserved.")
return
end
if (token:json_type_of("access_token") ~= 1) or (token:string_of_equals("access_token", "", true)) then
print("The response did not contain an access token. The existing cache was preserved.")
return
end
local obtained = chilkat.DateTime.new()
obtained:set_from_current_system_time()
token:update_string("obtained_at", obtained:get_as_timestamp(false))
-- The token response includes expires_in (seconds). Refresh before the access token expires.
-- The file contains credentials: use a private, access-controlled directory.
success = token:write_file("qa_data/tokens/office365.json")
if not success then
print("Could not save the token file.")
return
end
print("Credentials saved in the private working directory.")