如何在MVC中发送电子邮件异步

时间:2013-10-18 00:12:10

标签: c# asp.net-mvc email asynchronous

在我的系统中,我需要发送大量电子邮件。但是,如果我等待发送所有电子邮件,页面会变得太慢。我曾尝试创建一个异步类 - 但是,在发送电子邮件之前,类会启动并死掉。

 public class NotificationManager
    {
        public void SendNotification(NotificationData data) 
        {
           data.MailTo = new WorkflowManager().GetEmailNotification((StatusType)data.Issue.StatusID, data.Issue.IssueId);

                Task.Factory.StartNew(() =>
                {
                    new MailManager().SendMessage(data);
                });

        }
    }

class MailManager
    {
        static ILog log = log4net.LogManager.GetLogger(typeof(MailManager));

        public static void SendMessage(Models.Extensions.NotificationData data)
        {

            var domain = string.Format("{0}/{1}", HttpContext.Current.Request.Url.AbsoluteUri.Replace("Edit", "IssueDetail"), data.Issue.IssueCode);
            string type = new TypeManager().GetTypeById(data.Issue.IssueTypeID).Name;
            string status = new StatusManager().GetStatusById(data.Issue.IssueTypeID).Name;

            var body = string.Format("<h2>[{3}]</h2><br/>{0}<br/><br/><a href='{1}'>Issue</a><br/>[Ticket Number: {2}]", 
                data.Issue.Description, domain, data.Issue.IssueCode, type);

            var subject = string.Format("[{0}] {1}", status, data.Issue.Summary);

            SendEmailAwaitable(data.MailTo, subject, body);

            log.Error("End Send Email Async");

        }


        private async Task<bool> SendEmailAwaitable(List<MailAddress> To, string Subject, string Body, bool isBodyHtml = true)
        {
            Settings s = new Settings();
            MailMessage message = new MailMessage();
            MailAddress fromAddress = new MailAddress(s.Email, s.EmailDisplayName);

            SmtpClient smtpClient = new SmtpClient();
            NetworkCredential basicCredential = new NetworkCredential(s.EmailUserName, s.EmailPassword);

            string userToken = Subject;
            smtpClient.Host = s.EmailServer;
            smtpClient.UseDefaultCredentials = false;
            smtpClient.Credentials = basicCredential;

            message.From = fromAddress;
            message.Subject = Subject;

            message.IsBodyHtml = isBodyHtml;
            message.Body = Body;

            foreach (var item in To)
            {
                userToken += ":To: " + item.Address;
                message.To.Add(item);
            }
            smtpClient.SendCompleted += smtpClient_SendCompleted;
            smtpClient.SendAsync(message, null);
            await Task.Yield();
            return true;
        }

0 个答案:

没有答案