'SmtpClient Email Not Sent, Not Caught and Not Logged?

Our website was meant to send out a particular email, it didnt send the email and it also did not log the error which is unusual as i have a try catch setup which should log the entry in the try or catch section.

1) Why did it not log? Should i not use Exception and instead use SmtpException and SmptFailedException. If i have this would it have made a difference? If so can you please provide an example.

2) The port we are currently using is 587. As our website is SSL i read we should be using 443 port instead. Would this have made a difference?

The below code is called asynchronously by using

 ThreadPool.QueueUserWorkItem(new WaitCallback(SendInstructions), guid);

Which then calls a function that then calls the SendEmail Function below

public static bool SendEmail(String strToAddress, String strFromAddress, String strFromName, String strSubject, String strRecipientName, String strBody, String strEmbeddedImagePath, String strEmbeddedImageName, String strCCReminderEmail)
{
try
    {
        SmtpClient client = new SmtpClient();
        client.EnableSsl = true;

        using (MailMessage message = new MailMessage(
            new MailAddress(strFromAddress, strFromName),
            new MailAddress(strToAddress, strRecipientName)))
        {
            message.IsBodyHtml = true;
            message.Subject = strSubject;
            message.Body = strBody;

            if (!string.IsNullOrEmpty(strCCReminderEmail))
                message.CC.Add(strCCReminderEmail);

            client.Send(message);

            LogEmail(strFromAddress, strToAddress, strSubject, "Sent", strBody);
            return true;
        }
    }
    catch (Exception ex)
    {
        //log email
       LogEmail(strFromAddress, strToAddress, strSubject, "Error", strBody);
        throw;
    }

}



Solution 1:[1]

I had a problem similar when using

ThreadPool.QueueUserWorkItem( new WaitCallback(  ... 

and then

System.Net.Mail.SmtpClient sC = new System.Net.Mail.SmtpClient(SMTPHost, SMTPPort);

the thread died without throwing an exception.

In my case, the main application thread is exiting before the background threads in the threadpool have had a chance to finish.

The threadpool creates Background worker threads which die as soon as the main application thread terminates.

so I made a function to sleep 5 seconds and it worked.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Suraj Rao