All Indy SMTP examples I have seen show
TIdSMTP being instantiated at the start of the email send routine and freed at the end.
I have written an SMTP email sender prototype application, based upon Indy 10 components, that normally works with no issues. (It can send in the clear or via explicit or implicit TLS.) It instantiates
TIdSMTP on startup and frees it on closing.
I have just had a situation where
IdSMTP.Send threw an exception saying that SMTP was not connected. This would be unremarkable except for the fact that I have a test for
IdSMTP.Connected, immediately prior to my
IdSMTP.Send, that reported that SMTP was connected. My program could no longer be made to send emails because it thought it was connected but in reality it wasn't. The only solution was to restart the program. When testing of this prototype application is completed the code will be incorporated into a server service that cannot just be restarted to fix this sort of problem.
The problem could have been avoided or, at least, worked around if I had instantiated my
TIdSMTP class within my email send procedure; in the unlikely event of this re-occurring the
IdSMTP object would be freed at the end of the procedure and re-instantiated the next time it gets called.
The reason I didn't architect my solution as in the examples was that re-instantiation of
TIdSMTP for each email send also requires that the
IdSMTP object reconnect to the email server for each send. This can be a very slow process - of the order of 5 to 10 seconds for external email servers - and this overhead can be avoided by not re-instantiating
TIdSMTP each time.
So my question is: is this (or similar issues) the reason why all examples show re-instantiation each time? Or, is it simply to show a complete, contained example? The latter was how I interpreted it.
If you have experience with the pros and cons of this issue, please provide your opinions, and thoughts.
If there exists a definitive best practice, that would useful to hear about too.