0

In my system, I need send lot of emails. But, if I wait to send all the emails, the page gets too slow. I have tried to create an async class - but, the class starts and dies before the emails are even sent.

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

0 回答 0