0 votes

It happens occasionally that, sending mails using the method SendMessage(IMail email) of class Smtp, the execution flow never returns from it locking the entire application.

What could be the problem and how can it be solved or diagnosed so that the method returns at least an error through ISendMessageResult eventually after timeout expiration?

(in the code snippet i set the timeout for the Smtp object but it does not seem to work)

code snippet for sending email:

using (Smtp smtpClient = new Smtp())
{
    // Timeout in secondi 
    TimeSpan sendTimout = new TimeSpan(0, 0, 30);

    smtpClient.SendTimeout = sendTimout;

    if (ConnectToMailServer(
        smtpClient, 
        _encryptionType, 
        _username, _password, 
        _server, _port) && messaggio.To.Count>0)
    {
        _log.Info("Sending mail");
        ISendMessageResult result = smtpClient.SendMessage(
            messaggio);
        _log.Info("Email sending result: " + result);

        smtpClient.Close();

        if (result.Status == SendMessageStatus.Success)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    else
    {
        return false;
    }
}

Executing the code, logging stops at the "ISendMessageResult result = smtpClient.SendMessage(messaggio);" statement, even though there is a log right at the next statement, and the mail is never sent.

After restarting the blocked application, the same mail was sent succesfully.

by

1 Answer

0 votes

Smtp.SendMessage may throw an exception in case of network problems. Please wrap your code in try...catch statement.

You may additionally turn on logging to check the exact client-server communication:

https://www.limilabs.com/blog/logging-in-mail-dll

Note that:

Smtp.SendTimeout gets or sets the amount of time the underlying Socket will wait for a send bytes operation to complete successfully. There is also Smtp.ReceiveTimeout which specifies the amount of time the underlying Socket will wait to receive data once a read operation is initiated. Those properties are for low level read/write to Socket operations.

by (297k points)
...