vikingben
vikingben

Reputation: 1652

Send Email Async

This is what I've tried for sending email using the SendAsync() method. When passing the bool to send regular email it works fine. When sending with the SendAsync method no dice. Just looking for some tips if you see something wrong here. Thanks in advance.

private static void SendEmail(System.Net.Mail.MailMessage m, Boolean Async)
    {

    using (var smtpClient = new System.Net.Mail.SmtpClient(EmailList.SMTP_GOOGLE, 587))
            {
                smtpClient.EnableSsl = true;
                smtpClient.UseDefaultCredentials = false;
                smtpClient.Credentials = new NetworkCredential("[email protected]","password");
                smtpClient.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
                smtpClient.Timeout = 3000000;


                if (Async)
                {
                    object userState = m;
                    smtpClient.SendCompleted += new SendCompletedEventHandler(Smtp_OnComplete);
                    try
                    {
                        smtpClient.SendAsync(m, userState);
                    }
                    catch (Exception ex)
                    {
                            //Logging

                    }
                }
                else
                {
                    try
                    {
                        smtpClient.Send(m);
                    }
                    catch (Exception ex)
                        //Logging

                    }
                }
            }
        }

Upvotes: 0

Views: 2724

Answers (2)

jvdub
jvdub

Reputation: 927

I just set up a simple console app to run the methods for testing

Because the email is being sent asynchronously, the console app will start the method to in a different thread and continue with its own execution. If it closes before the method to send the actual email completes, the email will fail to send because Visual Studio will kill that thread. Try adding the following line after your call to send the email to make the console app wait a few seconds:

System.Threading.Thread.Sleep(5000);

This should be more than long enough for the email method to send the email and finish before the console app closes and Visual Studio kills all processes. The code should work fine on a web server.

Upvotes: 1

SLaks
SLaks

Reputation: 887195

Your using statement is disposing the SmtpClient before the asynchronous send finishes.
That won't work.

Instead, you can either use C# 5 await to wait for the async send to finish inside the using statement, or get rid of using entirely for async sends and dispose the SmtpClient in the completion event.

Upvotes: 11

Related Questions