Example #1
0
        public void Send(string content)
        {
            _smtpClient = new SmtpClient(Address, Port);
            _smtpClient.Credentials = new NetworkCredential(Account, Password);
            _smtpClient.EnableSsl = false;
            MailMessage mailMessage = new MailMessage();
            mailMessage.BodyEncoding = Encoding.UTF8;
            mailMessage.From = new MailAddress(From, SenderName, Encoding.UTF8);
            mailMessage.To.Add(To);
            mailMessage.Body = content;
            mailMessage.Subject = Subject;
            _smtpClient.Send(mailMessage);


            dynamic email = new Email("Example");
            email.To = "*****@*****.**";
            email.Send();


            var viewsPath = Path.GetFullPath(@"..\..\Views");

            var engines = new ViewEngineCollection();
            engines.Add(new FileSystemRazorViewEngine(viewsPath));

            var service = new EmailService(engines);
            dynamic email = new Email("Test");

            // Will look for Test.cshtml or Test.vbhtml in Views directory.
            email.Message = "Hello, non-asp.net world!";
            service.Send(email);
           // RESTORE DATABASE is terminating abnormally.
        }
		public async Task NotifyPlayerForAttention(string userId, string subject, string message, string gameId)
		{
			var userClaims = await _userManager.GetClaimsAsync(userId);

			var emailClaim = userClaims.FirstOrDefault(claim => claim.Type == ClaimTypes.Email);

			if (emailClaim == null)
				return;

			dynamic email = new Email("HailUser");
			email.To = emailClaim.Value;
			email.Subject = subject;
			email.Message = message;
            email.GameId = gameId;

			var service = new Postal.EmailService(System.Web.Mvc.ViewEngines.Engines, () =>
			{
				if (string.IsNullOrWhiteSpace(SMTPServer) || string.IsNullOrWhiteSpace(SMTPUsername) || string.IsNullOrWhiteSpace(SMTPPassword) || string.IsNullOrWhiteSpace(SMTPPort))
				{
					return new SmtpClient();
				}

				return new SmtpClient(SMTPServer, int.Parse(SMTPPort))
				{
					EnableSsl = true,
					Credentials = new NetworkCredential(SMTPUsername, SMTPPassword)
				};
			});

			await service.SendAsync(email);
		}
Example #3
0
        /// <summary>
        ///
        /// </summary>
        public void CheckInactive()
        {
            var userDb = new ApplicationDbContext();

            var lastDate     = DateTime.Today.AddDays(-180);
            var approvedDate = DateTime.Today.AddDays(14);

            // alle die sich 180 Tage nicht angemeldet haben
            // und die noch noch nicht benachrichtigt wurden
            // d.h. kein Approved-Datum haben
            // (das ist das Datum, an dem sie abgeschaltet werden)
            // nur Studenten
            var inactiveUsers = userDb.Users.Where(x =>
                                                   x.LastLogin.HasValue && x.LastLogin.Value < lastDate &&
                                                   !x.Approved.HasValue && x.MemberState == MemberState.Student).ToList();

            var email = new InactivityReportEmail()
            {
                To    = "*****@*****.**",
                Count = inactiveUsers.Count
            };


            var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails"));
            var engines   = new ViewEngineCollection();
            var engine    = new FileSystemRazorViewEngine(viewsPath);

            engines.Add(engine);
            var emailService = new Postal.EmailService(engines);

            // Rendern und senden
            emailService.Send(email);
        }
Example #4
0
        public JsonResult SendNotificationMails()
        {
            var notifsToSend = this.serviceActivity.GetNotificationsToSend();

            foreach (var notif in notifsToSend)
            {
                if (notif.Notifications != null && notif.Notifications.Count > 0)
                {
                    dynamic email = new Email("Worn");
                    email.To            = notif.User.Email;
                    email.Username      = notif.User.DisplayName;
                    email.ServerUrl     = string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"));
                    email.Notifications = notif.Notifications;

                    var emailService = new Postal.EmailService();
                    var message      = emailService.CreateMailMessage(email);
                    //email.Send();
                    this.serviceMail.SendMail(message);
                }
            }
            return(new JsonResult()
            {
                Data = true, JsonRequestBehavior = JsonRequestBehavior.AllowGet
            });
        }
        public void SendAync_returns_a_Task_and_sends_email()
        {
            var dir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            Directory.CreateDirectory(dir);
            try
            {
                using (var smtp = new SmtpClient())
                {
                    smtp.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;
                    smtp.PickupDirectoryLocation = dir;
                    smtp.Host = "localhost"; // HACK: required by SmtpClient, but not actually used!

                    var renderer = new Mock<IEmailViewRenderer>();
                    var parser = new Mock<IEmailParser>();
                    var service = new EmailService(renderer.Object, parser.Object, () => smtp);
                    parser.Setup(p => p.Parse(It.IsAny<string>(), It.IsAny<Email>()))
                          .Returns(new MailMessage("*****@*****.**", "*****@*****.**"));

                    var sending = service.SendAsync(new Email("Test"));
                    sending.Wait();

                    Directory.GetFiles(dir).Length.ShouldEqual(1);
                }
            }
            finally
            {
                Directory.Delete(dir, true);
            }
        }
Example #6
0
        public Task SendAsync(IdentityMessage message)
        {
            Postal.EmailService emailService = new Postal.EmailService(ViewEngines.Engines);

            var fromEmail = SecureSettings.GetValue("smtp:From");
            var host = SecureSettings.GetValue("smtp:Host");
            if (!string.IsNullOrEmpty(host))
            {
                emailService = new Postal.EmailService(ViewEngines.Engines, () => CreateMySmtpClient());
            }

            dynamic email = new Email("IdentityMessageService");
            email.To = message.Destination;
            if (!string.IsNullOrEmpty(fromEmail))
            {
                email.From = fromEmail;
            }
            else
            {
                fromEmail = ConfigurationManager.AppSettings["NoReplyEmail"];
                if (string.IsNullOrEmpty(fromEmail)) fromEmail = "*****@*****.**";
                email.From = fromEmail;
            }

            email.Subject = message.Subject;
            email.Body = message.Body;

            return emailService.SendAsync(email);

               // return email.SendAsync();

            //return Task.FromResult(0);
        }
        public static void NotifyNewComment(int commentId)
        {
            var currentCultureName = Thread.CurrentThread.CurrentCulture.Name;
            if (currentCultureName != "es-ES")
            {
                throw new InvalidOperationException(String.Format("Current culture is {0}", currentCultureName));
            }

            // Prepare Postal classes to work outside of ASP.NET request
            var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails"));
            var engines = new ViewEngineCollection();
            engines.Add(new FileSystemRazorViewEngine(viewsPath));

            var emailService = new EmailService(engines);

            // Get comment and send a notification.
            using (var db = new MailerDbContext())
            {
                var comment = db.Comments.Find(commentId);

                var email = new NewCommentEmail
                {
                    To = "*****@*****.**",
                    UserName = comment.UserName,
                    Comment = comment.Text
                };

                emailService.Send(email);
            }
        }
Example #8
0
 public static void Initialize(string viewsPath)
 {
     var engines = new ViewEngineCollection
     {
         new FileSystemRazorViewEngine(viewsPath)
     };
     service = new EmailService(engines);
 }
 private static string GetEmailForNote(TicketEventNotification note)
 {
     var email = new TicketEmail { Ticket = note.TicketEvent.Ticket, SiteRootUrl = RootUrl};
     var mailService = new EmailService();
     SerializableMailMessage message = mailService.CreateMailMessage(email);
     using (var ms = new MemoryStream())
     {
         new BinaryFormatter().Serialize(ms, message);
         return Convert.ToBase64String(ms.ToArray());
     }
 }
Example #10
0
        public Email(string viewName) : base(viewName)
        {
            var smtpServerUserName = ConfigurationManager.AppSettings["SmtpUsername"];
            var smtpServerPassword = ConfigurationManager.AppSettings["SmtpPassword"];

            var client = new SmtpClient();

            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.Credentials    = new NetworkCredential(smtpServerUserName, smtpServerPassword);
            emaiService           = new EmailService(ViewEngines.Engines, () => client);
        }
Example #11
0
        protected BaseMailService()
        {
            Logger = LogManager.GetLogger("Mail");

            UserService = new UserInfoService();

            var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails"));
            var engines   = new ViewEngineCollection();
            var engine    = new FileSystemRazorViewEngine(viewsPath);

            engines.Add(engine);
            EmailService = new Postal.EmailService(engines);
        }
Example #12
0
        static void Main()
        {
            var engines = new ViewEngineCollection
                          {
                              new ResourceRazorViewEngine(typeof(Program).Assembly, @"ResourceSample.Resources.Views")
                          };

            var service = new EmailService(engines);

            dynamic email = new Email("Test");
            email.Message = "Hello, non-asp.net world!";
            service.Send(email);
        }
        public void CreateMessage_returns_MailMessage_created_by_parser()
        {
            var renderer = new Mock<IEmailViewRenderer>();
            var parser = new Mock<IEmailParser>();
            var service = new EmailService(renderer.Object, parser.Object, () => null);
            var email = new Email("Test");
            var expectedMailMessage = new MailMessage();
            parser.Setup(p => p.Parse(It.IsAny<string>(), email)).Returns(expectedMailMessage);
            
            var actualMailMessage = service.CreateMailMessage(email);

            actualMailMessage.ShouldBeSameAs(expectedMailMessage);
        }
Example #14
0
        // Sending email using postal.mvc5 package
        public void SendEmail(IEnumerable<FileDetail> fileList)
        {
            var viewsPath = Path.GetFullPath(@"..\..\Views\Emails");

            var engines = new ViewEngineCollection();
            engines.Add(new FileSystemRazorViewEngine(viewsPath));

            var service = new EmailService(engines);

            dynamic email = new Email("FtpFiles");
            email.To = _emailRecipients;
            // Will look for Test.cshtml or Test.vbhtml in Views directory.
            email.Message = "Hello, non-asp.net world!";
            email.FileList = fileList;
            service.Send(email);
        }
        public void SendEmail(EmailModel email)
        {
            string viewsPath = GetEmailsTemplatePath();

            var engines = new ViewEngineCollection();
            engines.Add(new FileSystemRazorViewEngine(viewsPath));

            Log.Info("Creating email from {0} to {1} with subject {2}", email.From, email.From, email.Subject);
            var service = new EmailService(engines);
            MailMessage data = service.CreateMailMessage(email);

            var emailContent = new Email(email.To, email.From, email.CC, data.Subject, data.Body, data.IsBodyHtml,
                                         email.Type);

            _emailRepository.Save(emailContent);
        }
Example #16
0
        public static void Send()
        {
            var viewsPath = Path.GetFullPath(@"..\..\Views\Emails");

            var engines = new ViewEngineCollection();
            engines.Add(new FileSystemRazorViewEngine(viewsPath));

            var service = new EmailService(engines);

            MyEmail email = new MyEmail() { ViewName = "Test" };

            email.From = "*****@*****.**";
            email.To = "*****@*****.**";
            // Will look for Test.cshtml or Test.vbhtml in Views directory.
            //email.Message = "Hello, non-asp.net world!";
            service.Send(email);
        }
        public static void Notify(string to, string subject, string callbackUrl, int timeLeft)
        {
            var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails"));
            var engines   = new ViewEngineCollection();

            engines.Add(new FileSystemRazorViewEngine(viewsPath));

            var emailService = new Postal.EmailService(engines);
            var email        = new ReportCommentNotifyEmail
            {
                To          = to,
                Subject     = subject,
                CallbackUrl = callbackUrl,
                TimeLeft    = timeLeft
            };

            emailService.Send(email);
        }
Example #18
0
        protected BaseMailService()
        {
            /*
             * var smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
             * FromEMailAdress = $"{topic} <{smtpSection.From}>";
             */

            Logger = LogManager.GetLogger("Mail");

            UserService = new UserInfoService();

            var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails"));
            var engines   = new ViewEngineCollection();
            var engine    = new FileSystemRazorViewEngine(viewsPath);

            engines.Add(engine);
            EmailService = new Postal.EmailService(engines);
        }
        public async override void Run()
        {
            if (this.IsShuttingDown || this.Pause)
                return;

            var db = new SportsSystemDbContext();

            var participationService = new ParticipationService(db);

            var representativeUsers = await participationService.GetDeniedUsersNotification();



            //Prepare Postal classes to work outside of ASP.NET request
            var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails"));
            var engines = new ViewEngineCollection();
            engines.Add(new FileSystemRazorViewEngine(viewsPath));



            var emailService = new EmailService(engines);

            foreach (var competition in representativeUsers)
            {
                var email = new DeniedUsersNotifications
                {
                    ViewName = "DeniedUsers",
                    From = "*****@*****.**",
                    EndDate = competition.EndDate,
                    CompetitionName = competition.CompetitionName,
                    Subject = string.Format("رفع اشکالات مشخصات وارد شده {0}", competition.CompetitionName),
                    To = competition.Email,
                    FirstName = competition.FirstName,
                    LastName = competition.LastName,
                    University = competition.University,
                    DeniedCompetitors = competition.DeniedCompetitors,
                    DeniedTechnicalStaffs = competition.DeniedTechnicalStaffs
                };

                await emailService.SendAsync(email);
            }

            db.Dispose();
        }
Example #20
0
        public void SendMail(string to, string subject, string callbackUrl, string faculty)
        {
            var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails"));
            var engines   = new ViewEngineCollection();

            engines.Add(new FileSystemRazorViewEngine(viewsPath));

            var emailService = new Postal.EmailService(engines);

            var email = new FacultyAssignEmail
            {
                To          = to,
                Subject     = subject,
                CallbackUrl = callbackUrl,
                FacultyInfo = faculty
            };

            emailService.Send(email);
        }
Example #21
0
        public Email(string viewName) : base(viewName)
        {
            var tt = typeof(Email).Assembly;

            var engines = new System.Web.Mvc.ViewEngineCollection {
                new ResourceRazorViewEngine1(typeof(Email).Assembly, @"WatchRecruit.Web.Util.Views")
            };
            //engines.Add(new FileSystemRazorViewEngine(viewsPath));


            var smtpServerUserName = ConfigurationManager.AppSettings["SmtpUsername"];
            var smtpServerPassword = ConfigurationManager.AppSettings["SmtpPassword"];

            var client = new SmtpClient();

            client.DeliveryMethod = SmtpDeliveryMethod.Network;
            client.Credentials    = new NetworkCredential(smtpServerUserName, smtpServerPassword);
            client.EnableSsl      = true;
            emaiService           = new Postal.EmailService(engines, () => client);
            //emaiService = new Postal.EmailService(System.Web.Mvc.ViewEngines.Engines, () => client);
        }
Example #22
0
        static void Main(string[] args)
        {
            // Get the path to the directory containing views
            var viewsPath = Path.GetFullPath(@"..\..\Views");

            var engines = new ViewEngineCollection();
            engines.Add(new FileSystemRazorViewEngine(viewsPath));

            var service = new EmailService(engines);

            dynamic email = new Email("Test");
            email.Message = "Hello, non-asp.net world!";
            service.Send(email);

            // Alternatively, set the service factory like this:
            /*
            Email.CreateEmailService = () => new EmailService(engines);

            dynamic email = new Email("Test");
            email.Message = "Hello, non-asp.net world!";
            email.Send();
            */
        }
        public static void SendCorespondingEmail(Email email)
        {
            // ReSharper disable once AssignNullToNotNullAttribute

            /*var viewpath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails"));
             * var engines = new ViewEngineCollection();
             * engines.Add(new FileSystemRazorViewEngine(viewpath));
             * var emailService = new Postal.EmailService(engines);*/

            #region Setting Credentials using smtp client class instead of in web.config

            var client     = new SmtpClient();
            var credential = new NetworkCredential("*****@*****.**", "mangapi.");
            client.UseDefaultCredentials = false;
            client.Credentials           = credential;
            client.Host           = "smtp.gmail.com";
            client.Port           = 587;
            client.EnableSsl      = true;
            client.DeliveryMethod = SmtpDeliveryMethod.Network;

            var emailService = new Postal.EmailService(ViewEngines.Engines, () => client);

            #endregion

            try
            {
                //sending email using web.config credentials
                email.Send();

                //sending email using above credentials
                //emailService.Send(email);
            }
            catch (Exception exception)
            {
                ErrorLog.GetDefault(System.Web.HttpContext.Current).Log(new Error(new Exception(exception.Message)));
            }
        }
Example #24
0
        //http://aboutcode.net/postal/outside-aspnet.html
        //http://aboutcode.net/postal/multi-part.html
        //http://aboutcode.net/postal/
        public void SendPostalEmail(EmailAccount emailAccount, BasePostalMail mail, 
            IEnumerable<MailAttachment> attachments = null)
        {
            // Get the path to the directory containing views
            var viewsPath = CommonHelper.PostalViewPath;
           viewsPath = Path.GetFullPath(viewsPath);
            dynamic _mail = mail;
           
            var engines = new ViewEngineCollection();
            engines.Add(new FileSystemRazorViewEngine(viewsPath));
            using (var smtpClient = new SmtpClient())
            {
                smtpClient.UseDefaultCredentials = emailAccount.UseDefaultCredentials;
                smtpClient.Host = emailAccount.Host;
                smtpClient.Port = emailAccount.Port;
                smtpClient.EnableSsl = emailAccount.EnableSsl;
                if (emailAccount.UseDefaultCredentials)
                    smtpClient.Credentials = CredentialCache.DefaultNetworkCredentials;
                else
                    smtpClient.Credentials = new NetworkCredential(emailAccount.Username, emailAccount.Password);

                var service = new EmailService(engines, () => smtpClient);
                if (attachments != null)
                {
                    if (attachments.Count() > 0)
                    {
                        foreach (MailAttachment s in attachments)
                        {
                            mail.Attach(new Attachment(s.FileStream, s.Name, s.ContentType.MediaType));
                        }
                    }
                }
              


                service.Send(mail);


            }
          
          
          
        }
Example #25
0
       public MailMessage GetMailMessage(BasePostalMail mail)
        {
            dynamic _mail = mail;
            var emailService = new EmailService();
            var message = emailService.CreateMailMessage(mail);
           
            return message;

        }
Example #26
0
        public JsonResult SendNotificationMails()
        {
            var notifsToSend = this.serviceActivity.GetNotificationsToSend();
            foreach (var notif in notifsToSend)
            {
                if (notif.Notifications != null && notif.Notifications.Count > 0)
                {
                    dynamic email = new Email("Worn");
                    email.To = notif.User.Email;
                    email.Username = notif.User.DisplayName;
                    email.ServerUrl = string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"));
                    email.Notifications = notif.Notifications;

                    var emailService = new Postal.EmailService();
                    var message = emailService.CreateMailMessage(email);
                    //email.Send();
                    this.serviceMail.SendMail(message);

                }

            }
            return new JsonResult() { Data = true, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }
Example #27
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="receiverList"></param>
        /// <param name="sender"></param>
        /// <param name="model"></param>
        public void SendMail(ICollection <ApplicationUser> receiverList, ApplicationUser sender, MailJobModel model)
        {
            var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails"));
            var engines   = new ViewEngineCollection();
            var engine    = new FileSystemRazorViewEngine(viewsPath);

            engines.Add(engine);
            var emailService = new Postal.EmailService(engines);


            // Das Mail-Model aufbauen
            var mailModel = new CustomBodyEmail()
            {
                From               = sender.Email,
                Subject            = model.Subject,
                Body               = model.Body,
                IsImportant        = model.IsImportant,
                IsDistributionList = model.IsDistributionList,
                ListName           = model.ListName
            };

            foreach (var attachment in model.Files)
            {
                MemoryStream ms = new MemoryStream(attachment.Bytes);

                var a = new System.Net.Mail.Attachment(ms, attachment.FileName);

                mailModel.Attachments.Add(a);
            }


            // 1 Mail für jeden
            var deliveryModel = new MailDeliverSummaryReportModel();
            var errorCount    = 0;

            foreach (var user in receiverList)
            {
                // Mails werden nur versendet, wenn die Mail Adresse bestätigt ist
                if (!user.EmailConfirmed)
                {
                    // In den Bericht aufnehmen
                    errorCount++;
                    deliveryModel.Deliveries.Add(new MailDeliveryReportModel
                    {
                        User = user,
                        DeliverySuccessful = false,
                        ErrorMessage       = "Mailadresse nicht bestätigt. Grund: " + user.AccountErrorMessage
                    });
                }
                else
                {
                    // hier erst auf Like E-Mail überprüfen
                    // wenn die E-Mail unwichtig ist und der benutzer keine E-Mail erhalten möchte
                    // dann bekommt er auch keine - es wird aber im Versandprotokoll vermerkt
                    if (!model.IsImportant && !user.LikeEMails)
                    {
                        errorCount++;
                        deliveryModel.Deliveries.Add(new MailDeliveryReportModel
                        {
                            User = user,
                            DeliverySuccessful = false,
                            ErrorMessage       = "Benutzer möchte keine E-Mails erhalten"
                        });
                    }
                    else
                    {
                        mailModel.To = user.Email;

                        // Versand versuchen
                        try
                        {
                            emailService.Send(mailModel);

                            deliveryModel.Deliveries.Add(new MailDeliveryReportModel
                            {
                                User = user,
                                DeliverySuccessful = true,
                            });
                        }
                        catch (Exception ex)
                        {
                            errorCount++;
                            var strError = string.Format("Fehler bei Versand. Grund: {0}. Mailadresse wird auf ungültig gesetzt.", ex.Message);

                            deliveryModel.Deliveries.Add(new MailDeliveryReportModel
                            {
                                User = user,
                                DeliverySuccessful = false,
                                ErrorMessage       = strError
                            });

                            /*
                             * user.EmailConfirmed = false;
                             * // Ein Expiry ist nicht sinnvoll / möglich, da E-Mail Adresse ja ohnehin nicht erreichbar
                             * user.Remark = strError;
                             * user.Submitted = DateTime.Now;
                             * UserManager.Update(user);
                             */
                        }
                    }
                }
            }

            // Kopie an Absender
            mailModel.To = sender.Email;

            // Versandbericht nur an Staff
            if (sender.MemberState == MemberState.Staff)
            {
                var ms     = new MemoryStream();
                var writer = new StreamWriter(ms, Encoding.Default);

                writer.Write(
                    "Name;Vorname;E-Mail;Versand;Bemerkung");

                writer.Write(Environment.NewLine);

                foreach (var delivery in deliveryModel.Deliveries)
                {
                    writer.Write("{0};{1};{2};{3};{4}",
                                 delivery.User.LastName, delivery.User.FirstName, delivery.User.Email,
                                 delivery.DeliverySuccessful ? "OK" : "FEHLER",
                                 delivery.ErrorMessage);
                    writer.Write(Environment.NewLine);
                }

                writer.Flush();
                writer.Dispose();

                var sb = new StringBuilder();
                sb.Append("Versandbericht");
                sb.Append(".csv");

                var bytes = ms.GetBuffer();
                var ms2   = new MemoryStream(bytes);

                var a = new System.Net.Mail.Attachment(ms2, sb.ToString());

                mailModel.Attachments.Add(a);
            }

            try
            {
                emailService.Send(mailModel);
            }
            finally { }
        }
Example #28
0
        static void Main(string[] args)
        {
            bool quietMode = false;
            foreach (var arg in args)
            {
                if (arg.ToUpperInvariant().Contains("Q")) quietMode = true;
            }

            try
            {

                Console.WriteLine("Program starting" + (quietMode ? " in quiet mode" : "") + "....");
                DateTime lastDate = DateTime.Now.AddDays(-Convert.ToInt32(ConfigurationManager.AppSettings["days"]));
                var storedDate = DataAccess.GetKeyValue("lastemail").Value;
                if (!string.IsNullOrEmpty(storedDate))
                {
                    lastDate = Convert.ToDateTime(storedDate);
                }
                Console.WriteLine("Last Run: {0:M/d/yyyy h:mm tt}", lastDate);
                Console.WriteLine("Looking for verses....");
                var verses = DataAccess.GetRecentVerses(lastDate);
                Console.WriteLine("Looking for terms....");
                var terms = DataAccess.GetRecentTerms(lastDate);
                Console.WriteLine("Looking for files....");
                var files = FileUtility.Recent(lastDate);
                Console.WriteLine("Looking for email addresses....");
                var emails = DataAccess.GetEmails();

                verses = (verses != null ? verses.Take(50) : new List<ScriptureItem>());
                terms = (terms != null ? terms.Take(50) : new List<GlossaryItem>());
                files = (files != null ? files.Take(50) : new List<FileInfoResult>());

                bool sendEmail = ((verses.Count() > 0 || terms.Count() > 0 || files.Count() > 0) && emails != null && emails.Count() > 0);

                if (!sendEmail)
                {
                    Console.WriteLine();
                    if (!quietMode)
                    {
                        Console.WriteLine("Nothing new. Not sending email. Press any key to exit.");
                        Console.Read();
                    }
                    else
                    {
                        Console.WriteLine("Nothing new. Not sending email.");
                    }
                    Environment.Exit(0);
                }

                Console.WriteLine("Preparing email....");
                var viewsPath = ConfigurationManager.AppSettings["TemplatePath"];

                var engines = new ViewEngineCollection();
                var razorEngine = new FileSystemRazorViewEngine(viewsPath);
                engines.Add(razorEngine);

                var service = new EmailService(engines);

                NotifyEmail email = new NotifyEmail("Notification");
                var webroot = ConfigurationManager.AppSettings["AbsoluteRoot"];
                email.AbsoluteRoot = webroot.EndsWith("/") ? webroot.Substring(0, webroot.Length - 1) : webroot;
                email.To = string.Join(", ", emails.Select(x=>x.Email).ToArray());
                email.Verses = verses;
                email.Terms = terms;
                email.Files = files;

                bool withAttachments = false;
                if (files != null)
                {
                    long limit = Convert.ToInt64(ConfigurationManager.AppSettings["AttachmentLimitInMB"]) * 1000 * 1024;
                    if (files.Sum(x => x.Length) <= limit)
                    {
                        withAttachments = true;
                        foreach (var file in files)
                        {
                            var root = ConfigurationManager.AppSettings["FilesRoot"];
                            if (root.EndsWith("/")) root = root.Remove(root.Length - 1);
                            var fullName = file.Path.Replace("/", @"\");
                            if (!fullName.StartsWith(@"\")) fullName = @"\" + fullName;
                            fullName = root + fullName;

                            email.Attach(new Attachment(fullName));
                        }
                    }
                }
                email.HasAttachments = withAttachments;
                service.Send(email);

                var newDate = DateTime.Now.ToString("M/d/yyyy h:mm tt");
                DataAccess.UpdateKeyValue("lastemail", newDate);

                Console.WriteLine();
                Console.WriteLine("Sent an email to {0} addresses with {1} verses, {2} terms, {3} files ({4}) and updated the date for next time.", emails.Count(), verses.Count(), terms.Count(), files.Count(), withAttachments ? "with attachments" : "no attachments");

                Console.WriteLine();
                if (!quietMode)
                {
                    Console.WriteLine("Press any key to exit.");
                    Console.Read();
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                if (!quietMode)
                {
                    Console.WriteLine("Press any key to exit.");
                    Console.Read();
                }
            }
        }
        public async override void Run()
        {
            if (this.IsShuttingDown || this.Pause)
                return;


            using (var db = new SportsSystemDbContext())
            {

                //Prepare Postal classes to work outside of ASP.NET request
                var viewsPath = Path.GetFullPath(HostingEnvironment.MapPath(@"~/Views/Emails"));

                var engines = new ViewEngineCollection
                {
                    new FileSystemRazorViewEngine(viewsPath)
                };

                var emailService = new EmailService(engines);

                var competitionService = new CompetitionService(db);

                var readyCompetitions = await competitionService.GetReadyCompetitionsNotificationAsync();

                foreach (var readyCompetition in readyCompetitions)
                {
                    var email = new CompetitionNotificationEmail
                    {
                        ViewName = "ReadyCompetition",
                        From = "*****@*****.**",
                        StartDate = readyCompetition.StartDate.Value,
                        EndDate = readyCompetition.EndDate.Value,
                        CompetitionName = readyCompetition.CompetitionName,
                        Subject = string.Format("فراخوان برای اعلام آمادگی در {0}", readyCompetition.CompetitionName),
                        SiteUrl = IaunSportsSystemApp.GetSiteRootUrl()
                    };

                    foreach (var representativeUser in readyCompetition.RepresentativeUsers)
                    {
                        email.To = representativeUser.Email;
                        email.FirstName = representativeUser.FirstName;
                        email.LastName = representativeUser.LastName;
                        email.University = representativeUser.University;
                        email.Password = EncryptionHelper.Decrypt(representativeUser.Password, EncryptionHelper.Key);
                        await emailService.SendAsync(email);
                    }

                }


                var registerCompetitions = await competitionService.GetRegisterCompetitionsNotification();

                foreach (var registerCompetition in registerCompetitions)
                {
                    var email = new CompetitionNotificationEmail
                    {
                        ViewName = "RegisterCompetition",
                        From = "*****@*****.**",
                        StartDate = registerCompetition.StartDate.Value,
                        EndDate = registerCompetition.EndDate.Value,
                        CompetitionName = registerCompetition.CompetitionName,
                        Subject = string.Format("فراخوان برای ثبت نام در {0}", registerCompetition.CompetitionName),
                        SiteUrl = IaunSportsSystemApp.GetSiteRootUrl()
                    };

                    foreach (var representativeUser in registerCompetition.RepresentativeUsers)
                    {
                        email.To = representativeUser.Email;
                        email.FirstName = representativeUser.FirstName;
                        email.LastName = representativeUser.LastName;
                        email.University = representativeUser.University;
                        email.Password = EncryptionHelper.Decrypt(representativeUser.Password, EncryptionHelper.Key);
                        await emailService.SendAsync(email);
                    }

                }


                var printCardCompetitions = await competitionService.GetPrintCardCompetitionsNotification();

                foreach (var printCardCompetition in printCardCompetitions)
                {
                    var email = new CompetitionNotificationEmail
                    {
                        ViewName = "PrintCardCompetition",
                        From = "*****@*****.**",
                        StartDate = printCardCompetition.StartDate.Value,
                        EndDate = printCardCompetition.EndDate.Value,
                        CompetitionName = printCardCompetition.CompetitionName,
                        Subject = string.Format("فراخوان برای چاپ کارت  {0}", printCardCompetition.CompetitionName),
                        SiteUrl = IaunSportsSystemApp.GetSiteRootUrl()
                    };

                    foreach (var representativeUser in printCardCompetition.RepresentativeUsers)
                    {
                        email.To = representativeUser.Email;
                        email.FirstName = representativeUser.FirstName;
                        email.LastName = representativeUser.LastName;
                        email.University = representativeUser.University;
                        email.Password = EncryptionHelper.Decrypt(representativeUser.Password, EncryptionHelper.Key);
                        await emailService.SendAsync(email);
                    }

                }

            }

        }