Skip to content

How to log the TIDSmtp component

I have some Delphi code that needs to send a quick mail message so I was using the Indy 10 TIdSmtp component.  The code was working just fine for a few months, but this week it would fail with an EIdSMTPReplyError exception.  The message property of the exception was a empty string, not terribly useful.  After a bit of googling, I found references to using one of the Indy TIdLogXXXX components.  Sure enough, there is a TIdLogFile component that will log messages to a file.  That sounded like what I needed, but the help file did not make it clear on how to hook up a TIdLogFile to a TIdSmtp component.

I did some searching and found a blog post by Marshall Fryman on his Ruminated Rumblings blog that a great example of how to hook up one of the Indy logging components.  What I needed to do was to create an instance of the TIdSmtp’s IOHandler property and assign the TIdLogFile to the IOHandler.Intercept property.  He also recommended assigning the IOHandler.OnStatus event to TIdLogFile.OnStatus event

The way my code ended up was something like this:

      try
        try
          IdLogFile.Active := true;
          fsmtp.IOHandler := TIdIOHandler.MakeDefaultIOHandler(fsmtp);
          fsmtp.IOHandler.Intercept := IdLogFile;
          fsmtp.IOHandler.OnStatus  := fsmtp.OnStatus;
          fSMTP.Connect;
          fSMTP.Send(fMessage);
        except
          on e: exception do begin
            MessageDlg(‘Error sending message: ‘ + e.Message, mtError, [mbOK], 0);
          end;
        end;
      finally
        if fSMTP.Connected then
          fSMTP.Disconnect(true);
        IdLogFile.Active := false;
      end;