how to send mails asynchronous? [duplicate]

若如初见. 提交于 2019-12-10 12:11:47

问题


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);
        }
    }
}

I've this code, but i'd like to improve it in way that i could send mails asynchronous. Could you suggest any idea to improve this piece of code or other way to do it. I've tried asynchronous properties that visual studio suggested but couldn't use them.


回答1:


SmtpClient allows you to send asynchronously, and uses events to notify you when the send completes. This can be unweildy to use, so you can create an extension method to return a Task instead:

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;
}

To get the result of the send task you can use 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
    }
});



回答2:


Wild guess, but SendAsync might do the job!




回答3:


Change your code from:

 client.Send(msg);

To:

client.SendAsync(msg);

more details

link1

link2



来源:https://stackoverflow.com/questions/15140308/how-to-send-mails-asynchronous

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