0
namespace Binarios.admin
{
    public class SendEmailGeral
    {
        public SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
        public MailMessage msg = new MailMessage();

        public void Enviar(string sendFrom, string sendTo, string subject, string body)
        {    
            string pass = "12345";
            System.Net.NetworkCredential smtpCreds = new System.Net.NetworkCredential(sendFrom, pass);

            //setup SMTP Host Here
            client.UseDefaultCredentials = false;
            client.Credentials = smtpCreds;
            client.EnableSsl = true;

            MailAddress to = new MailAddress(sendTo);
            MailAddress from = new MailAddress(sendFrom);

            msg.IsBodyHtml = true;
            msg.Subject = subject;
            msg.Body = body;
            msg.From = from;
            msg.To.Add(to);

            client.Send(msg);
        }
    }
}

我有这段代码,但我想改进它,以便我可以异步发送邮件。您能否提出任何想法来改进这段代码或其他方式来做到这一点。我尝试了 Visual Studio 建议但无法使用的异步属性。

4

3 回答 3

11

SmtpClient允许您异步发送,并在发送完成时使用事件通知您。这使用起来可能很笨拙,因此您可以创建一个扩展方法来返回 a Task

public static Task SendAsync(this SmtpClient client, MailMessage message)
{
    TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
    Guid sendGuid = Guid.NewGuid();

    SendCompletedEventHandler handler = null;
    handler = (o, ea) =>
    {
        if (ea.UserState is Guid && ((Guid)ea.UserState) == sendGuid)
        {
            client.SendCompleted -= handler;
            if (ea.Cancelled)
            {
                tcs.SetCanceled();
            }
            else if (ea.Error != null)
            {
                tcs.SetException(ea.Error);
            }
            else
            {
                tcs.SetResult(null);
            }
        }
    };

    client.SendCompleted += handler;
    client.SendAsync(message, sendGuid);
    return tcs.Task;
}

要获得发送任务的结果,您可以使用ContinueWith

Task sendTask = client.SendAsync(message);
sendTask.ContinueWith(task => {
    if(task.IsFaulted) {
        Exception ex = task.InnerExceptions.First();
        //handle error
    }
    else if(task.IsCanceled) {
        //handle cancellation
    }
    else {
        //task completed successfully
    }
});
于 2013-02-28T16:24:56.523 回答
1

疯狂的猜测,但SendAsync可能会完成这项工作!

于 2013-02-28T16:19:47.303 回答
0

更改您的代码:

 client.Send(msg);

至:

client.SendAsync(msg);

更多细节

链接1

链接2

于 2013-02-28T16:20:26.183 回答