Multithreaded Mail Sender

Download source code - Delphi and C++Builder

//Delphi
procedure TSmtpWorkItem.Execute(AThread: TThread);
var
  ds: TDataSet;
  cnt: Integer;
begin
  try
    SetupSmtp(FSmtp);
 
    LogMessage('Open: ' + FConnectionString);
    FSmtp.Open();
    try
      ds := CreateDataSet();
      try
        ds.First();
        cnt := 0;
 
        while (not ds.Eof) do
        begin
          if IsStop() then Break;
 
          LogMessage('Send ' + IntToStr(cnt) + ': ' + FConnectionString);
          ComposeEmail(ds);
          try
            SendEmail();
          except
            on EclSocketError do
            begin
              FSmtp.Close();
              FSmtp.Open();
            end;
          end;
 
          Inc(cnt);
          ds.Next();
        end;
      finally
        ds.Free();
      end;
    finally
      FSmtp.Close();
      LogMessage('Close: ' + FConnectionString);
    end;
  finally
    FSynchronizer.Synchronize(SyncThreadDone);
  end;
end;
//C++Builder
void __fastcall TSmtpWorkItem::Execute(Classes::TThread*)
{
  __try
  {
    SetupSmtp(m_smtp);
 
    LogMessage("Open: " + m_connectionString);
    m_smtp->Open();
    __try
    {
      TDataSet *ds = CreateDataSet();
      __try
      {
        ds->First();
        int cnt = 0;
         
        while (!ds->Eof)
        {
          if (IsStop())
            break;
 
          LogMessage("Send " + IntToStr(cnt) + ": " + m_connectionString);
          ComposeEmail(ds);
          try
          {
            SendEmail();
          }
          catch (EclSocketError&)
          {
            m_smtp->Close();
            m_smtp->Open();
          }
 
          cnt++;
          ds->Next();
        }
      }
      __finally
      {
        delete ds;
      }
    }
    __finally
    {
      m_smtp->Close();
      LogMessage("Close: " + m_connectionString);
    }
  }
  __finally
  {
    m_synchronizer->Synchronize(SyncThreadDone);
  }
}

Add Feedback