From sgcIndy 2024.5.0 the XOAuth2 Authentication mechanism is supported. The SASL XOAUTH2 mechanism for use with the IMAP AUTHENTICATE, POP AUTH, and SMTP AUTH commands. This mechanism allows the use of OAuth 2.0 Access Tokens to authenticate to a user's Gmail account for example.
The TIdSASLXOAuth2 has the event OnAuthenticate which is called before the Authorization is done. The event has 2 parameters:
xOAuth2 := TIdSASLXOAUTH2.Create(nil); smtp := TIdSMTP.Create(nil); ... smtp.AuthType := satSASL; smtp.SASLMechanisms.Clear; smtp.SASLMechanisms.Add.SASL := xoauth2;
After configuring the SMTP and XOAuth2 components, send an email using the SMTP component and when the Authorization is required the event OnAuthenticate is called. Just set here the Username and the Access Token.
procedure OnXOAuth2Authenticate(Sender: TObject; var Username, Token: string); begin Token := 'OAuth2 Access Token'; Username := 'your mail account'; end;
The OAuth2 Access Token can be obtained using the TsgcHTTP_OAuth2_Client from the sgcWebSockets library.
Find below an example of how configure the OAuth2 client to obtain an OAuth2 Access Token from your google user account.
OAuth2 := TsgcHTTP_OAuth2_Client.Create(nil); OAuth2.OnAfterAccessToken := OnOAuth2AfterAccessTokenEvent; OAuth2.OAuth2Options.GrantType := auth2CodePKCE; OAuth2.LocalServerOptions.IP := '127.0.0.1'; OAuth2.LocalServerOptions.Port := 0; OAuth2.AuthorizationServerOptions.AuthURL := 'https://accounts.google.com/o/oauth2/auth'; OAuth2.AuthorizationServerOptions.TokenURL := 'https://accounts.google.com/o/oauth2/token'; OAuth2.AuthorizationServerOptions.Scope.Text := 'https://mail.google.com/'; OAuth2.OAuth2Options.ClientId := '<your oauth2 client id>'; OAuth2.OAuth2Options.ClientSecret := '<your oauth2 client secret>'; OAuth2.Start; procedure OnOAuth2AfterAccessTokenEvent(Sender: TObject; const Access_Token, Token_Type, Expires_In, Refresh_Token, Scope, RawParams: String; var Handled: Boolean); begin ShowMessage(Access_Token); end;
Find below a demo that shows the XOAuth2 component with the OAuth2 Client from the sgcWebSockets library to send an email using the SMTP Protocol. Select the tab XOAuth2 to use this type of Authentication and fill the fields:
When you subscribe to the blog, we will send you an e-mail when there are new updates on the site so you wouldn't miss them.