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.
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.
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.
TsgcMailOAuth2 (unit sgcAuth_Mail_OAuth2)
SASL OAUTHBEARER (RFC 7628) and XOAUTH2
Windows, macOS, Linux, iOS, Android
Enterprise and All-Access, plus the sgcAuth pack. Also available in sgcWebSockets .NET.
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);
The OAuth2 part of modern mail, wrapped in one component with the provider details already filled in.
Provider selects mopMicrosoft365 or mopGmail with the right endpoints. mopCustom takes CustomAuthURL, CustomTokenURL, CustomDeviceAuthorizationURL and CustomScope for any other provider.
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.
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.
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.
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.
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.
Authoritative sources for the standards this component implements.
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. | Open | |
| 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. | Open | |
| Technical Document (PDF) Features, quick start, code samples for Delphi & C++ Builder and primary-source references for this component only. | Open | |
| User Manual (PDF) Comprehensive manual covering every component in the library. | Open | |
| Blog: Delphi Login With Passkeys, SAML SSO, LDAP and TOTP 2FA How the six authentication components fit together in one Delphi application. | Open |