中异步发送电子邮件

中异步发送电子邮件

本文介绍了在 C# 中异步发送电子邮件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在开发一个应用程序,用户在窗口中的某个按钮上单击/按下 Enter,该应用程序会进行一些检查并确定是否发送几封电子邮件,然后显示另一个带有消息的窗口.

I'm developing an application where a user clicks/presses enter on a certain button in a window, the application does some checks and determines whether to send out a couple of emails or not, then show another window with a message.

我的问题是,发送 2 封电子邮件会显着减慢进程速度,并且在进行发送时第一个窗口在大约 8 秒内看起来冻结了.

My issue is, sending out the 2 emails slows the process noticeably, and for some (~8) seconds the first window looks frozen while it's doing the sending.

有什么办法可以让我在后台发送这些电子邮件并立即显示下一个窗口?

Is there any way I can have these emails sent on the background and display the next window right away?

请不要用使用 X 类"或仅使用 X 方法"来限制您的回答,因为我还不太熟悉该语言,希望能提供更多信息.

Please don't limit your answer with "use X class" or "just use X method" as I am not all too familiarized with the language yet and some more information would be highly appreciated.

谢谢.

推荐答案

As of .NET 4.5 SmtpClient 实现异步等待方法SendMailAsync.因此,异步发送电子邮件如下:

As of .NET 4.5 SmtpClient implements async awaitable methodSendMailAsync.As a result, to send email asynchronously is as following:

public async Task SendEmail(string toEmailAddress, string emailSubject, string emailMessage)
{
    var message = new MailMessage();
    message.To.Add(toEmailAddress);

    message.Subject = emailSubject;
    message.Body = emailMessage;

    using (var smtpClient = new SmtpClient())
    {
        await smtpClient.SendMailAsync(message);
    }
}

这篇关于在 C# 中异步发送电子邮件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 16:45