public static Mailout GetByID(int MailoutID, IEnumerable <string> includeList = null)
        {
            Mailout obj = null;
            string  key = cacheKeyPrefix + MailoutID + GetCacheIncludeText(includeList);

            Mailout tmpClass = null;

            if (Cache.IsEnabled)
            {
                if (Cache.IsEmptyCacheItem(key))
                {
                    return(null);
                }
                tmpClass = Cache[key] as Mailout;
            }

            if (tmpClass != null)
            {
                obj = tmpClass;
            }
            else
            {
                using (Entities entity = new Entities())
                {
                    IQueryable <Mailout> itemQuery = AddIncludes(entity.Mailout, includeList);
                    obj = itemQuery.FirstOrDefault(n => n.MailoutID == MailoutID);
                }
                Cache.Store(key, obj);
            }

            return(obj);
        }
        public static string GetNewsletterText(Mailout mailout)
        {
            string body = EmailTemplateService.HtmlMessageBody("~/EmailTemplates/Newsletter/EmailTextWrapper.txt", new { FullCompanyName = Globals.Settings.CompanyName, FullPhysicalMailAddress = Settings.CustomPhysicalMailAddress });

            body = InsertDynamicContent(mailout, body, mailout.BodyText).Replace("&amp;", "&").Replace("[[ROOT]]", Helpers.RootPath);             //Plain text does not convert the ampersand
            return(body);
        }
        public static void SendNewsletterTest(int newsletterID, int?newsletterDesignID, int newsletterFormatID, string email, string mailServer, string mailFrom, string approvalCode)
        {
            NewsletterDesign newsletterDesign =
                ((newsletterDesignID == null) ? null : NewsletterDesign.GetByID((int)newsletterDesignID));

            if (newsletterID <= 0)
            {
                throw new Exception("Newsletter Id must be greater than 0");
            }
            Newsletter newsletter = Newsletter.GetByID(newsletterID);

            string           subject = newsletter.Title;
            SubscriptionType type    = SubscriptionType.Html;          //default

            if (!string.IsNullOrEmpty(approvalCode))
            {
                switch (newsletterFormatID)
                {
                case 1:
                    subject = "Html Newsletter Approval: " + subject;
                    type    = SubscriptionType.Html;
                    break;

                case 2:
                    subject = "Text Newsletter Approval: " + subject;
                    type    = SubscriptionType.PlainText;
                    break;

                case 3:
                    subject = "Multipart Newsletter Approval: " + subject;
                    type    = SubscriptionType.MultiPart;
                    break;

                default:
                    throw new Exception("Newsletter Format " + newsletterFormatID + " not defined.");
                }
            }

            Queue <SubscriberInfo> subscriber = new Queue <SubscriberInfo>();

            string[] recipients = email.Split(',');
            foreach (string i in recipients)
            {
                subscriber.Enqueue(new SubscriberInfo(i, type));
            }

            Mailout mailout  = MailoutFromNewsletter(newsletter, newsletterDesign.NewsletterDesignID);
            string  body     = GetNewsletterHtml(mailout, true).Replace("[[EntityID]]", "");
            string  bodyText = GetNewsletterText(mailout).Replace("[[EntityID]]", "");
            AttachmentCollection attachments = null;
            EmailSender          es          = new EmailSender(subject, subscriber, mailFrom, mailServer, bodyText, body, attachments);

            es.EnableLogging = false;
            es.Send();
        }
        public static bool ForwardNewsletter(int mailoutID, Guid entityID, string toEmail, string fromEmail, string toName, string fromName)
        {
            Mailout mailout = Mailout.GetByID(mailoutID);

            if (mailout == null)
            {
                throw new Exception("The requested mailout does not exist");
            }

            NewsletterSendingTypeFormat sendingFormat = Settings.NewsletterSendingType;

            SubscriptionType type;

            switch (sendingFormat)
            {
            case NewsletterSendingTypeFormat.HtmlAndText:                     // when forwarding, we don't ask for a preferred format, so default to HTML
            case NewsletterSendingTypeFormat.HtmlOnly:
                type = SubscriptionType.Html;
                break;

            case NewsletterSendingTypeFormat.TextOnly:
                type = SubscriptionType.PlainText;
                break;

            case NewsletterSendingTypeFormat.Multipart:
                type = SubscriptionType.MultiPart;
                break;

            default:
                throw new Exception("Newsletter Format " + sendingFormat + " not defined.");
            }

            SubscriberInfo recipient = new SubscriberInfo(toEmail, type);

            String forwardPreambleText = "This newsletter was forwarded to you by " + fromName + " (" + fromEmail + ")\n";
            String forwardPreambleHtml = "<p>" + forwardPreambleText + "</p>";

            string body     = forwardPreambleHtml + GetNewsletterHtml(mailout, true).Replace("[[EntityID]]", "");
            string bodyText = forwardPreambleText + GetNewsletterText(mailout);
            string subject  = "FW: " + mailout.Title;

            if (SendSingleEmail(recipient, Settings.SenderEmail, subject, body, bodyText))
            {
                Subscriber subscriberEntity = Subscriber.GetSubscriberByEntityID(entityID);
                if (subscriberEntity != null)
                {
                    NewsletterAction.CreateForwardAction(subscriberEntity, mailoutID, toEmail);
                }

                return(true);
            }

            return(false);
        }
 public Mailout(Mailout objectToCopy)
 {
     Body         = objectToCopy.Body;
     BodyText     = objectToCopy.BodyText;
     Description  = objectToCopy.Description;
     DesignID     = objectToCopy.DesignID;
     DisplayDate  = objectToCopy.DisplayDate;
     Issue        = objectToCopy.Issue;
     Keywords     = objectToCopy.Keywords;
     MailoutID    = objectToCopy.MailoutID;
     NewsletterID = objectToCopy.NewsletterID;
     Timestamp    = objectToCopy.Timestamp;
     Title        = objectToCopy.Title;
 }
        private static Mailout SaveNewMailoutForNewsletter(Newsletter newsletter, List <MailingList> lists, int designId)
        {
            Mailout mailout = MailoutFromNewsletter(newsletter, designId);

            mailout.Save();

            foreach (MailingList mailingList in lists)
            {
                MailoutMailingList mml = new MailoutMailingList();
                mml.MailoutID     = mailout.MailoutID;
                mml.MailingListID = mailingList.MailingListID;
                mml.Save();
            }

            return(mailout);
        }
        /// <summary>
        /// Send a Newsletter to a collection of mailing lists, or resend a previously sent Mailout to its collection of mailing lists
        /// </summary>
        /// <param name="newsletterId">The ID of the Newsletter to send</param>
        /// <param name="existingMailoutId">The ID of an existing Mailout to resend</param>
        /// <param name="designId">The ID of the design to wrap the newsletter content</param>
        /// <param name="mailingLists">Collection of mailing lists to send the mailout to</param>
        /// <param name="notSentSubscribers">Collection of subscribers who had invalid email addresses</param>
        /// <returns>True if at least one subscriber was sent the newsletter, false otherwise</returns>
        public static bool SendNewsletter(int?newsletterId, int?existingMailoutId, int designId, List <MailingList> mailingLists, out List <MailingListSubscriber> notSentSubscribers)
        {
            notSentSubscribers = new List <MailingListSubscriber>();

            Mailout mailout;

            if (existingMailoutId.HasValue)
            {
                mailout = Mailout.GetByID(existingMailoutId.Value);
            }
            else if (newsletterId.HasValue)
            {
                Newsletter newsletter = Newsletter.GetByID(newsletterId.Value);
                mailout = SaveNewMailoutForNewsletter(newsletter, mailingLists, designId);
            }
            else
            {
                return(false);
            }

            String htmlBodyWithDesign = GetNewsletterHtml(mailout, true);
            String textBody           = GetNewsletterText(mailout);

            List <int> mailingListIds = mailingLists.Select(ml => ml.MailingListID).ToList();

            Queue <SubscriberInfo> uniqueSubscribers = SubscriberInfo.GetMailingListSubscribersWithEmailsByListOfMailingListIDs(mailingListIds, existingMailoutId);

            if (uniqueSubscribers.Count > 0)
            {
                EmailSender es = new EmailSender(
                    mailout.Title,
                    uniqueSubscribers,
                    Settings.SenderEmail,
                    Settings.MailServer,
                    textBody,
                    htmlBodyWithDesign
                    , null);
                es.IPAddress      = HttpContext.Current.Request.UserHostAddress;
                es.MailoutID      = mailout.MailoutID;
                es.MailingListIDs = mailingListIds;
                es.Send();
                EmailSender.SendEmailJobs.Add(es);

                return(true);
            }
            return(false);
        }
        /// <summary>
        /// This method transforms a Newsletter into a Mailout, optionally replacing the Newsletter's design
        /// </summary>
        /// <param name="newsletter">The Newsletter entity to copy</param>
        /// <param name="designId">The design to override the DesignID property of the Newsletter (optional)</param>
        /// <returns>An unsaved Mailout with a copy of the Newsletter's data</returns>
        public static Mailout MailoutFromNewsletter(Newsletter newsletter, int?designId)
        {
            Mailout mailout = new Mailout();

            mailout.Timestamp    = DateTime.UtcNow;
            mailout.NewsletterID = newsletter.NewsletterID;
            mailout.Body         = newsletter.Body.Replace("& ", "&amp; ");
            mailout.BodyText     = newsletter.BodyText;
            mailout.Description  = HttpContext.Current != null?HttpContext.Current.Server.HtmlEncode(newsletter.Description) : newsletter.Description.Replace("& ", "&amp; ");

            mailout.DesignID    = designId.HasValue ? designId.Value : newsletter.DesignID;
            mailout.DisplayDate = newsletter.DisplayDate;
            mailout.Issue       = HttpContext.Current != null?HttpContext.Current.Server.HtmlEncode(newsletter.Issue) : newsletter.Issue.Replace("& ", "&amp; ");

            mailout.Keywords = HttpContext.Current != null?HttpContext.Current.Server.HtmlEncode(newsletter.Keywords) : newsletter.Keywords.Replace("& ", "&amp; ");

            mailout.Title = newsletter.Title.Replace("& ", "&amp; ");
            return(mailout);
        }
        /// <summary>
        /// This method wraps the body of the newsletter in the desired design and replaces placeholder tags with dynamic content
        /// </summary>
        /// <param name="mailout">The Mailout containing the newsletter data to be sent</param>
        /// <param name="email">Whether this newsletter should be formatted for sending out via email (vs. web-only display)</param>
        /// <returns></returns>
        public static string GetNewsletterHtml(Mailout mailout, bool email)
        {
            string       body          = string.Empty;
            const string trackingImage = @"<img src=""[[ROOT]]newsletter-opened.aspx?entityId=[[EntityID]]&amp;mailoutId=[[MailoutID]]"" height=""1"" width=""1"" border=""0"" />";

            NewsletterDesign newsletterDesign = NewsletterDesign.GetByID(Convert.ToInt32(mailout.DesignID));

            if (newsletterDesign != null)
            {
                if (newsletterDesign.Path != null)
                {
                    body = EmailTemplateService.HtmlMessageBody("~/" + newsletterDesign.Path, new { FullCompanyName = Globals.Settings.CompanyName, FullPhysicalMailAddress = Settings.CustomPhysicalMailAddress });
                    //The final remove is necessary to get rid of the "Trouble viewing this email" stuff from the Newsletter frontend pages
                    if (!email)
                    {
                        body = body.Remove(body.IndexOf("[[Email Only]]"), body.IndexOf("[[End Email Only]]") - body.IndexOf("[[Email Only]]") + "[[End Email Only]]".Length);
                    }
                    else
                    {
                        body = body.Replace("[[Email Only]]", "")
                               .Replace("[[End Email Only]]", "") + trackingImage;
                    }
                }
                else if (newsletterDesign.Template != null)
                {
                    body = newsletterDesign.Template;
                }
                else
                {
                    throw new Exception("No design path or html for selected design");
                }
                body = InsertDynamicContent(mailout, body, mailout.Body);

                // For front-end display, remove per-subscriber replacement tags
                if (!email)
                {
                    body = body.Replace("[[EntityID]]", "");
                }
            }
            return(body.Replace("[[ROOT]]", Helpers.RootPath));
        }
        private static String InsertDynamicContent(Mailout mailout, String messageBody, String body)
        {
            string newsletterLink  = "[[ROOT]]newsletter-details.aspx?mailoutId=" + mailout.MailoutID;
            string linkToSite      = Globals.Settings.LinkToSite;
            string unsubscribeLink = "[[ROOT]]newsletter-unsubscribe.aspx?entityId=[[EntityID]]&amp;mailoutId=[[MailoutID]]";
            string forwardLink     = "[[ROOT]]newsletter-forward.aspx?entityId=[[EntityID]]&amp;mailoutId=[[MailoutID]]";

            messageBody = messageBody
                          .Replace("[[NewsletterTitle]]", mailout.Title)
                          .Replace("[[NewsletterBody]]", body)
                          .Replace("[[NewsletterIssue]]", mailout.Issue)
                          .Replace("[[NewsletterDate]]", Helpers.ConvertUTCToClientTime(mailout.DisplayDate).ToShortDateString())
                          .Replace("[[NewsletterSender]]", Settings.SenderEmail)
                          .Replace("[[NewsletterLink]]", newsletterLink)
                          .Replace("[[LinkToSite]]", linkToSite);

            messageBody = Helpers.ReplaceRootWithAbsolutePath(messageBody);
            messageBody = ReplaceLinksWithTrackingLinks(messageBody);
            messageBody = messageBody.Replace("[[UnsubscribeLink]]", unsubscribeLink);             // track unsubscribes and forwards separately from regular click-throughs
            messageBody = messageBody.Replace("[[ForwardLink]]", forwardLink);
            messageBody = messageBody.Replace("[[MailoutID]]", mailout.MailoutID.ToString());
            return(Helpers.ReplaceRootWithAbsolutePath(messageBody));
        }