unit Api.ServiceImpl;

interface

uses
  XData.Server.Module,
  XData.Service.Common,

  IdSMTP, IdMessage, IdSSLOpenSSL, IdText, IdExplicitTLSClientServerBase,
  IdIOHandlerSocket, IdException, IdSSL, IdSMTPBase, IdGlobal, IdStack, IdWinsock2,
  IdStackConsts, IdIOHandler, IdIOHandlerStack, IdBaseComponent,
  IdComponent, IdTCPConnection, IdTCPClient, IdMessageClient, VCL.Forms, Api.Service;

type
  [ServiceImplementation]
  TApiService = class(TInterfacedObject, IApiService)
  public
    function SendEmail(Name, Email, Subject, Body: string): string;
  end;

implementation

uses
  System.SysUtils,
  System.IniFiles,
  Common.Logging,
  Main;


function TApiService.SendEmail(Name, Email, Subject, Body: string): string;
var
  SMTP: TIdSMTP;
  Message: TIdMessage;
  SSL: TIdSSLIOHandlerSocketOpenSSL;
  IniFile: TIniFile;
  IniPath, HtmlBody: string;
begin
  IniPath := ChangeFileExt(Application.ExeName, '.ini');
  IniFile := TIniFile.Create(IniPath);
  try
    SMTP := TIdSMTP.Create(nil);
    Message := TIdMessage.Create(nil);
    SSL := TIdSSLIOHandlerSocketOpenSSL.Create(SMTP);
    try
      SMTP.IOHandler := SSL;
      SMTP.UseTLS := utUseExplicitTLS;
      SMTP.AuthType := satDefault;

      SMTP.Host := IniFile.ReadString('SMTP', 'Host', '');
      SMTP.Port := IniFile.ReadInteger('SMTP', 'Port', 0);
      SMTP.Username := IniFile.ReadString('SMTP', 'Username', '');
      SMTP.Password := IniFile.ReadString('SMTP', 'Password', '');

      SSL.SSLOptions.Method := sslvTLSv1_2;
      SSL.SSLOptions.SSLVersions := [sslvTLSv1_2];

      Message.From.Address := IniFile.ReadString('SMTP', 'EmailWebsiteUses', '');
      Message.Recipients.EmailAddresses := IniFile.ReadString('SMTP', 'RecipientEmail', '');
      Message.Subject := Subject;

      HtmlBody := Format(
        '<html>' +
        '<body style="font-family: Arial, sans-serif; font-size: 14px;">' +
        '<h2 style="color: #2E86C1;">New Contact Form Message from EM Systems Website</h2>' +
        '<hr>' +
        '<p><strong><u>Submitted On:</u></strong> %s</p>' +
        '<p><strong><u>From:</u></strong> %s &lt;%s&gt;</p>' +
        '<p><strong><u>Subject:</u></strong> %s</p>' +
        '<hr>' +
        '<p style="margin-top: 20px;"><strong>Message:</strong></p>' +
        '<p>%s</p>' +
        '</body></html>',
        [FormatDateTime('yyyy-mm-dd hh:nn AM/PM', Now), Name, Email, Subject, Body.Replace(sLineBreak, '<br>')]
      );

      Message.Body.Text := HtmlBody;
      Message.ContentType := 'text/html';

      SMTP.Connect;
      try
        SMTP.Send(Message);
      finally
        SMTP.Disconnect;
      end;

      Logger.Log(1, Format('Contact form submitted. Name: %s, Email: %s, Subject: %s, Message: %s', [Name, Email, Subject, Body]));
    finally
      SSL.Free;
      Message.Free;
      SMTP.Free;
    end;
  finally
    IniFile.Free;
  end;

  Result := 'Email sent successfully';
end;






initialization
  RegisterServiceType(TApiService);

end.

