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 Lazarus Pascal Downloads
program ChilkatDemo;
// Demonstrates using the Chilkat Pascal wrapper via the C bridge DLL.
// Builds as a console application under Lazarus (FPC) or Delphi.
{$IFDEF FPC}
{$MODE DELPHI}
{$ENDIF}
{$APPTYPE CONSOLE}
uses
{$IFDEF UNIX}
cthreads,
{$ENDIF}
SysUtils,
CkDllLoader,
Chilkat.OAuth2,
Chilkat.JsonObject,
Chilkat.CkDateTime;
// ---------------------------------------------------------------------------
procedure RunDemo;
var
success: Boolean;
oauth: TOAuth2;
authUrl: string;
waited: Integer;
token: TJsonObject;
obtained: TCkDateTime;
begin
success := False;
// Assumes Chilkat is unlocked. See Global Unlock Sample.
oauth := TOAuth2.Create;
oauth.TokenEndpoint := 'https://login.microsoftonline.com/common/oauth2/v2.0/token';
oauth.ClientId := 'CLIENT_ID';
// A public desktop client does not have a client secret.
oauth.AuthorizationEndpoint := 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize';
oauth.LocalHost := 'localhost';
oauth.ListenPort := 3017;
oauth.CodeChallenge := True;
oauth.CodeChallengeMethod := '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';
success := oauth.AddAuthQueryParam('prompt','select_account');
if (success <> True) then
begin
WriteLn('Could not configure account selection.');
Exit;
end;
authUrl := oauth.StartAuth();
if (oauth.LastMethodSuccess <> True) then
begin
WriteLn('Could not start the loopback listener.');
Exit;
end;
success := oauth.LaunchBrowser(authUrl);
if (success <> True) then
begin
oauth.Cancel();
WriteLn('Could not open the system browser.');
Exit;
end;
waited := 0;
while ((oauth.AuthFlowState < 3) and (waited < 180000)) do
begin
oauth.SleepMs(200);
waited := waited + 200;
end;
if (oauth.AuthFlowState < 3) then
begin
oauth.Cancel();
WriteLn('Authorization timed out.');
Exit;
end;
if (oauth.AuthFlowState <> 3) then
begin
WriteLn('Authorization did not complete. Flow state: ' + oauth.AuthFlowState);
Exit;
end;
token := TJsonObject.Create;
success := token.Load(oauth.AccessTokenResponse);
if (success <> True) then
begin
WriteLn('Could not parse the token response.');
Exit;
end;
if ((token.JsonTypeOf('refresh_token') <> 1) or (token.StringOfEquals('refresh_token','',True) = True)) then
begin
WriteLn('No offline refresh token was issued. The existing cache was preserved.');
Exit;
end;
if ((token.JsonTypeOf('access_token') <> 1) or (token.StringOfEquals('access_token','',True) = True)) then
begin
WriteLn('The response did not contain an access token. The existing cache was preserved.');
Exit;
end;
obtained := TCkDateTime.Create;
obtained.SetFromCurrentSystemTime();
token.UpdateString('obtained_at',obtained.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.
success := token.WriteFile('qa_data/tokens/office365.json');
if (success <> True) then
begin
WriteLn('Could not save the token file.');
Exit;
end;
WriteLn('Credentials saved in the private working directory.');
oauth.Free;
token.Free;
obtained.Free;
end;
// ---------------------------------------------------------------------------
begin
try
RunDemo;
except
on E: Exception do
WriteLn('Unhandled exception: ', E.ClassName, ': ', E.Message);
end;
WriteLn;
{$IFDEF MSWINDOWS}
WriteLn('Press Enter to exit...');
ReadLn;
{$ENDIF}
end.