コード例 #1
0
ファイル: EmailsService.cs プロジェクト: cybermv/MailPig
        public IEnumerable<MailerResult> SendMailToGroup(int emailId, int groupId)
        {
            IRepository<Email> emailRepo = UnitOfWork.Repository<Email>();
            IRepository<GroupSubscription> groupSubscriptionsRepo = UnitOfWork.Repository<GroupSubscription>();

            Email emailToSend = emailRepo.FindById(emailId);
            List<GroupSubscription> groupSubscribers = groupSubscriptionsRepo.Query
                .Where(gs => gs.GroupId == groupId &&
                             !gs.DateLeft.HasValue)
                .Include(gs => gs.Subscriber)
                .ToList();

            // if email not found or no subscribers to send to, return null
            if (emailToSend == null || groupSubscribers.Count == 0)
            {
                return new[] { new MailerResult(MailerResultStatusEnum.Exception, "Invalid Id's specified!", null) };
            }

            List<MailPigEmail> emailsToDeliver = groupSubscribers
                .Select(gs => new MailPigEmail(
                    emailId,
                    gs.Id,
                    SenderEmail,
                    gs.Subscriber.Email,
                    emailToSend.Subject,
                    emailToSend.Body))
                .ToList();

            Mailer mailer = new Mailer();
            IEnumerable<MailerResult> results = mailer.SendBulk(emailsToDeliver);

            IRepository<SentEmail> sentEmailsRepo = UnitOfWork.Repository<SentEmail>();
            foreach (MailPigEmail mailPigEmail in emailsToDeliver)
            {
                if (mailPigEmail.SentSuccessfully)
                {
                    SentEmail sentMail = new SentEmail
                    {
                        DateSent = DateTime.Now,
                        EmailId = mailPigEmail.EmailId,
                        RecipientId = mailPigEmail.RecipientId
                    };
                    sentEmailsRepo.Insert(sentMail);
                }
            }

            return results.ToList();
        }