Delphi Mail OAuth2

Microsoft 365 and Gmail no longer accept a plain password for most mailboxes. Get the OAuth2 tokens, keep them fresh, and hand your SMTP, IMAP or POP3 client the exact SASL string it needs.

TsgcMailOAuth2

Obtains and refreshes the OAuth 2.0 access tokens for Exchange Online and Gmail, and builds the XOAUTH2 and OAUTHBEARER strings. It never talks to the mail server, so it works with Indy TIdSMTP, TIdIMAP4, TIdPOP3 or any library that can send a raw SASL command.

Component class

TsgcMailOAuth2 (unit sgcAuth_Mail_OAuth2)

Protocol

SASL OAUTHBEARER (RFC 7628) and XOAUTH2

Platforms

Windows, macOS, Linux, iOS, Android

Edition

Enterprise and All-Access, plus the sgcAuth pack. Also available in sgcWebSockets .NET.

Sign in once, send mail for months

Pick the Provider and the Protocols, set ClientId, reuse the stored refresh token or call Start, then authenticate the mail session with GetXOAuth2.

uses
  IdSMTP, sgcAuth_Mail_OAuth2;

// Mail is a form field: Mail: TsgcMailOAuth2;
procedure TForm1.FormCreate(Sender: TObject);
begin
  Mail := TsgcMailOAuth2.Create(Self);
  Mail.Provider := mopMicrosoft365;
  Mail.Protocols := [mpSMTP];
  Mail.TenantId := 'contoso.onmicrosoft.com';
  Mail.ClientId := 'your-application-id';
  Mail.OnTokensChanged := OnMailTokensChanged;

  // reuse the stored refresh token, sign in only when it no longer works
  Mail.RefreshToken := LoadRefreshToken;
  if (Mail.RefreshToken = '') or not Mail.Refresh then
    Mail.Start; // opens the browser, PKCE and a loopback redirect
end;

procedure TForm1.OnMailTokensChanged(Sender: TObject; const AccessToken,
  RefreshToken: String; const ExpiresAt: TDateTime);
begin
  SaveRefreshToken(RefreshToken); // encrypt it in your store
end;

// TIdSMTP with UseTLS = utUseExplicitTLS and AuthType = satNone
procedure TForm1.Authenticate(aSMTP: TIdSMTP);
begin
  aSMTP.Connect; // EHLO and STARTTLS
  aSMTP.SendCmd('AUTH XOAUTH2 ' + Mail.GetXOAuth2('user@contoso.com'), 235);
end;
// uses: IdSMTP, sgcAuth_Mail_OAuth2
TsgcMailOAuth2 *Mail = new TsgcMailOAuth2(this);
Mail->Provider = mopMicrosoft365;
Mail->Protocols = TsgcMailOAuth2Protocols() << mpSMTP;
Mail->TenantId = "contoso.onmicrosoft.com";
Mail->ClientId = "your-application-id";
Mail->OnTokensChanged = OnMailTokensChanged;

Mail->RefreshToken = LoadRefreshToken();
if (Mail->RefreshToken.IsEmpty() || !Mail->Refresh())
  Mail->Start();

IdSMTP1->Connect();
IdSMTP1->SendCmd("AUTH XOAUTH2 " + Mail->GetXOAuth2("user@contoso.com"), 235);

What's inside

The OAuth2 part of modern mail, wrapped in one component with the provider details already filled in.

Microsoft 365 and Gmail presets

Provider selects mopMicrosoft365 or mopGmail with the right endpoints. mopCustom takes CustomAuthURL, CustomTokenURL, CustomDeviceAuthorizationURL and CustomScope for any other provider.

Scopes from the protocols

Set Protocols to any mix of mpSMTP, mpIMAP and mpPOP3 and the component requests the matching scopes, with offline_access on Microsoft 365. GetScope shows what will be asked.

Browser or device code

Flow chooses mofAuthorizationCodePKCE (browser plus loopback redirect, see LocalServerOptions) or mofDeviceCode for services and consoles, where OnDeviceCode hands you the code and URL to show.

Token lifecycle

AccessToken, RefreshToken and ExpiresAt are always current. Refresh renews the access token synchronously and OnTokensChanged fires every time, so you can persist the new refresh token.

SASL strings ready to send

GetXOAuth2 and GetOAuthBearer return the Base64 initial responses for AUTH XOAUTH2 and AUTH OAUTHBEARER. The Raw variants and the sgcGetXOAuth2 functions help with debugging and other token sources.

Transport agnostic

The component never opens a mail connection. Use Indy TIdSMTP, TIdIMAP4 or TIdPOP3, or any mail library that can send a raw SASL command, with HTTPClientOptions for the TLS of the token requests.

Specifications & references

Authoritative sources for the standards this component implements.

Documentation & Demos

Deep-link to the component reference, grab the ready-to-run demo project, and download the trial.

Online Help: TsgcMailOAuth2 Full property, method and event reference, plus the Microsoft 365 and Gmail app registration steps.
Demo Project: Demos\26.Authentication\06.Mail_OAuth2 Browser and device code sign in, token refresh and a test mail sent with AUTH XOAUTH2. Ships inside the sgcWebSockets package, download the trial below.
Technical Document (PDF) Features, quick start, code samples for Delphi & C++ Builder and primary-source references for this component only.
User Manual (PDF) Comprehensive manual covering every component in the library.
Blog: Delphi Login With Passkeys, SAML SSO, LDAP and TOTP 2FA How the six authentication components fit together in one Delphi application.
Best value: All-AccessEvery eSeGeCe product, Premium Support included, from €1,059/year.
See All-Access pricing

Ready to Send Mail With OAuth2?

Download the free trial and keep your Delphi mail features working with Microsoft 365 and Gmail.