I have a working Delphi application that sends emails through Gmail’s SMTP servers using Indy components. The current implementation works fine but requires users to enable “Allow less secure apps” in their Google account settings.
I want to upgrade this solution to use OAuth 2.0 authentication instead of basic username/password authentication. This would eliminate the need for users to lower their security settings and comply with Google’s recommended security practices.
Here’s my current working code that uses basic authentication:
function TMainForm.SendMailMessage(SenderEmail, RecipientEmail, EmailSubject,
EmailContent, SMTPServer: String; SMTPPort: Integer; LoginName, LoginPass: String): Boolean;
begin
Result := False;
try
MailMessage := nil;
SSLHandler := nil;
SMTPClient := nil;
try
// Configure email message
try
MailMessage := TIdMessage.Create(nil);
MailMessage.From.Address := SenderEmail;
MailMessage.Recipients.EMailAddresses := RecipientEmail;
MailMessage.Subject := EmailSubject;
MailMessage.Body.Text := EmailContent;
except
Exception.RaiseOuterException(Exception.Create('Failed to configure email message'));
end;
// Setup SSL/TLS handler
try
SSLHandler := TIdSSLIOHandlersocketopenSSL.Create(nil);
SSLHandler.SSLOptions.Method := sslvTLSv1;
SSLHandler.SSLOptions.Mode := sslmUnassigned;
SSLHandler.SSLOptions.VerifyMode := [];
SSLHandler.SSLOptions.VerifyDepth := 0;
except
Exception.RaiseOuterException(Exception.Create('SSL configuration failed'));
end;
// Configure SMTP client
try
SMTPClient := TIdSMTP.Create(nil);
SMTPClient.IOHandler := SSLHandler;
SMTPClient.UseTLS := utUseExplicitTLS;
SMTPClient.Host := SMTPServer;
SMTPClient.Port := SMTPPort;
SMTPClient.Username := LoginName;
SMTPClient.Password := LoginPass;
except
Exception.RaiseOuterException(Exception.Create('SMTP setup failed'));
end;
try
SMTPClient.Connect;
try
SMTPClient.Send(MailMessage);
finally
SMTPClient.Disconnect;
end;
except
Exception.RaiseOuterException(Exception.Create('Email transmission failed'));
end;
finally
SMTPClient.Free;
SSLHandler.Free;
MailMessage.Free;
Result := True;
end;
except
on E: Exception do
begin
if E.InnerException <> nil then
ShowMessage('Error: ' + E.Message + #13#13 + E.InnerException.Message)
else
ShowMessage('Error: ' + E.Message);
end;
end;
end;
What modifications do I need to make to integrate OAuth 2.0 authentication with this Indy SMTP implementation?