如何发送邮件同步? [英] how to send mails asynchronous?

查看:286
本文介绍了如何发送邮件同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我有这个code,但我想改善它,我可以发送邮件的方式同步。
你可以建议任何想法,以改善这片code或其他的方式来做到这一点的。
我试过异步属性Visual Studio的建议,但不能使用它们。

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.

推荐答案

SmtpClient ,您可以异步发送,并使用事件发送完成时通知您。这可能是unweil​​dy使用,因此您可以创建一个扩展方法返回一个工作而不是:

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

要得到你可以使用发送任务的结果 ContinueWith

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

这篇关于如何发送邮件同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆