It is my understanding than an SMTPSocket needs to stay in scope until it has finished sending an email. In a Console app, I thought it was sufficient to add an SMTPSocket as a property of a module and use it when sending emails. This does not seem to work as emails are not sent. However, If I send the email, then use a loop with a DoEvents command and wait until the email is sent before exiting the method, the emails go out fine. Is this necessary or am I doing something wrong?
you need to make a loop with DoEvents and set a flag in MailSent event, so you know when to end the loop.
Or you use CURL Plugin which can be used synchronously.
That is exactly what I am doing.
In a desktop app, when you drag an SMTP object on to a window and use this object to send emails, there is no need to use a loop to wait for the emails to send. Why can’t you have an SMPT object as a property of a module in a Console app and do the same thing?
Check that you aren’t Diming the socket in your method. It’s something I do from time to time that bites me.
I just tried it by simply applying the example in the LR, and whether I use an SMTPSocket property
sendMailSocket as SMTPSocket of App or of a module, it works fine.
The loop to wait for the MailSent event is necessary to prevent the app to quit before the mail is actually sent.
Michel, I downloaded your example. Thank you. My app is structured differently. It scans a folder for files every 60 seconds and runs continually, so it does not quit before the emails are sent.
In the app.run event
app.DoEvents(1000 * 60)
In the ProcessFiles method, it will send an email if a file is processed. The only way the email will send is if I wait until the MailSent event fires while in the same method that is sending the email (just like you have in your example). It is fine and I can do this. I am just curious as to why the SMTP object does not send the emails if I exit the method, since the app is still running and the SMTP does not seem to be nil.
Console apps work a bit differently than desktop apps. As I understand it, in a console app, DoEvents is actually what is driving the event loop. So in order for things like asynchronous socket events to work properly, DoEvents needs to be running regularly for the socket code to process. So for mail to send it probably needs the event loop to be running faster than once a second. Have you tried smaller values, or leaving the parameter blank?
would be better. Sleeping too long will slow down sockets.
In a desktop app, the event loop is provided for you, which is why DoEvents is bad: the event loop is already running. In a console app, there is no event loop unless you create one yourself. This is what DoEvents was created for. In your example, your event loop is running too slowly. Perhaps you should put ProcessFiles into a Timer. That will allow you to sleep less in your event loop and keep everything running smoothly.