Two ways to send email via SmtpClient asynchronously, different results

爷,独闯天下 提交于 2019-12-04 03:38:14

Your fist method will not work properly because of the USING-block. After the using-block ends, the SmtpClient object will de disposed. So you can't get access to it in your event handler.

tips: 1-dont use "using block" for MailMessage objet, it dispose your object before mail sent
2-dispose MailMessage objects on SmtpClient.SendCompleted event:

smtpClient.SendCompleted += (s, e) =>
    {
        message.Dispose();
    };

3-set SendCompletedEventHandler for smtpClient object

smtpClient.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);

4-more code:

private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
    {
        // Get the unique identifier for this asynchronous operation.
        String token = (string)e.UserState;

        if (e.Cancelled)
        {
            //write your code here
        }
        if (e.Error != null)
        {
            //write your code here
        }
        else //mail sent
        {
            //write your code here
        }

        mailSent = true;
    }

SmtpClient.SendAsync is the preferred method of async email sending since it uses SmtpClient methods specially designed for this purpose. It is also simpler to implement and has been proven to work thousands of times.

Your 5 sec delay is strange and suggests there is a problem that needs addressing. First piece of code is just covering the problem up but does not eliminate it.

SmtpClient.SendAsync will actually only send asynchronously if your delivery method is not SpecifiedPickupDirectory or PickupDirectoryFromIis. In those cases it will write the message file into the pickup folder before returning. Check your config file's <smtp> section. My guess is you're using one of these methods and the problem is with the pickup folder. Delete old files you might have there and check if the problem is not your antivirus software which most likely searches each new file for viruses. Check if there is encryption or compression attributes set. Can be something else too. Best way to test if the folder is the source of the problems is by manually coping an email file into it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!