Thursday, August 07, 2008

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;

4 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. Spend a lot of time trying translate to C++/Builder line:

    fsmtp.IOHandler := TIdIOHandler.MakeDefaultIOHandler(fsmtp);

    always get an error in C++Builder :(

    ReplyDelete
  3. I wish I could help you, but I haven't touched C++ Builder in nearly 10 years. You may want to check the C++ Builder forums on CodeGear or one of the Indy forums on AtoZed's site.

    Which version or C++Builder are you using? I think the older versions had problems calling Delphi class methods.

    ReplyDelete

Note: Only a member of this blog may post a comment.