Exemplo n.º 1
0
        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("&", "&").Replace("[[ROOT]]", Helpers.RootPath);             //Plain text does not convert the ampersand
            return(body);
        }
Exemplo n.º 2
0
        /// <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));
        }
Exemplo n.º 3
0
        /// <summary>
        /// This method checks the Content Manager page for form fields.
        /// If it finds form fields it will submit them to the form recipient.
        /// </summary>
        public static void ParseRequestForFormFields(string regionName)
        {
            if (String.IsNullOrEmpty(HttpContext.Current.Request.Form[DynamicSubmitName]))
            {
                return;
            }
            int?   micrositeID   = null;
            bool   globalContact = false;
            CMPage cmPage        = CMSHelpers.GetCurrentRequestCMSPage();

            // determine legit fields
            List <CMPageRegion> prs = new List <CMPageRegion>();
            int?userID = Helpers.GetCurrentUserID();

            if (userID == 0)
            {
                userID = null;
            }
            if (cmPage != null)
            {
                CMRegion cmRegion = CMRegion.CMRegionPage(0, 1, "", "", true, new CMRegion.Filters {
                    FilterCMRegionName = regionName
                }).FirstOrDefault();
                if (cmRegion != null)
                {
                    CMPageRegion currentRegion = CMPageRegion.LoadContentRegion(new CMPageRegion.Filters {
                        FilterCMPageRegionCMRegionID = cmRegion.CMRegionID.ToString(), FilterCMPageRegionUserID = userID.ToString(), FilterCMPageRegionCMPageID = cmPage.CMPageID.ToString(), FilterCMPageRegionNeedsApproval = false.ToString()
                    });
                    if (currentRegion != null)
                    {
                        prs.Add(currentRegion);
                    }
                }
            }

            //Also get Global areas that might contain forms
            List <CMPage> globalAreas = CMSHelpers.GetCachedCMPages().Where(c => !c.CMTemplateID.HasValue && c.FileName.Equals(regionName)).ToList();
            List <CMPage> temp        = new List <CMPage>();

            temp.AddRange(globalAreas);
            foreach (CMPage globalPage in temp)
            {
                CMRegion cmRegion = CMRegion.CMRegionGetByName(regionName).FirstOrDefault();
                if (cmRegion != null)
                {
                    CMPageRegion region = CMPageRegion.LoadContentRegion(new CMPageRegion.Filters {
                        FilterCMPageRegionCMRegionID = cmRegion.CMRegionID.ToString(), FilterCMPageRegionUserID = userID.ToString(), FilterCMPageRegionCMPageID = globalPage.CMPageID.ToString(), FilterCMPageRegionNeedsApproval = false.ToString()
                    });
                    if (region != null)
                    {
                        prs.Clear();
                        prs.Add(region);
                    }
                    else
                    {
                        globalAreas.Remove(globalPage);
                    }
                }
                else
                {
                    globalAreas.Remove(globalPage);
                }
            }
            if (prs.Count > 0)
            {
                bool hasFields = false;

                List <string> validFields = new List <string>();
                List <string> checkBoxes  = new List <string>();

                foreach (CMPageRegion pr in prs)
                {
                    MatchCollection ms = Regex.Matches(pr.Content, @"<(input|textarea|select) (.|\n)*?name=""?((\w|\d|\s|\-|\(|\))+)""?(.|\n)*?/?>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                    if (ms.Count > 0 && globalAreas.Exists(c => c.CMPageID == pr.CMPageID))
                    {
                        cmPage        = globalAreas.Find(c => c.CMPageID == pr.CMPageID);
                        globalContact = true;
                    }
                    foreach (Match m in ms)
                    {
                        if (!m.ToString().Contains("type=\"radio\"") || !validFields.Contains(m.Groups[3].Value))
                        {
                            validFields.Add(m.Groups[3].Value);
                        }
                        if (m.ToString().Contains("type=\"checkbox\""))
                        {
                            checkBoxes.Add(m.Groups[3].Value);
                        }
                    }
                }

                validFields.Remove("dynamicsubmit");

                CMSubmittedForm newForm = new CMSubmittedForm();
                newForm.IsProcessed    = false;
                newForm.DateSubmitted  = DateTime.UtcNow;
                newForm.FormRecipient  = cmPage.FormRecipient;
                newForm.ResponsePageID = cmPage.ResponsePageID;
                newForm.CMMicrositeID  = cmPage.CMMicrositeID;

                if (HttpContext.Current.Request.Files.Count > 0)
                {
                    if (Regex.IsMatch(HttpContext.Current.Request.Files[0].FileName, "(\\.(doc)|(docx)|(pdf)|(jpg)|(jpeg)|(bmp)|(png)|(gif)|(ppt)|(pptx)|(xls)|(xlsx))$"))
                    {
                        HttpContext.Current.Request.Files[0].SaveAs(HttpContext.Current.Server.MapPath(UploadedFilesLocation + HttpContext.Current.Request.Files[0].FileName));
                        newForm.UploadedFile = HttpContext.Current.Request.Files[0].FileName;
                    }
                    else
                    {
                        Page page = (Page)HttpContext.Current.Handler;
                        page.ClientScript.RegisterStartupScript(page.GetType(), "InvalidFileExt", "alert('Invalid file extension.  Valid extensions are: doc,docx,pdf,jpg,jpeg,bmp,png,gif,ppt,pptx,xls,xlsx');", true);
                        return;
                    }
                }

                if (validFields.Count > 0)
                {
                    StringBuilder formData = new StringBuilder();
                    validFields.ForEach(s =>
                    {
                        if (HttpContext.Current.Request.Form[s] != null)
                        {
                            formData.Append(string.Format("<tr><td>{0}</td><td>{1}</td></tr>", s, HttpContext.Current.Request.Form[s].ToString()));
                            if (!hasFields)
                            {
                                hasFields = true;
                            }
                        }                                                                         // if the item is not posted, no harm, just dont include it
                        else if (checkBoxes.Contains(s))
                        {
                            formData.Append(string.Format("<tr><td>{0}</td><td>{1}</td></tr>", s, "off"));
                            if (!hasFields)
                            {
                                hasFields = true;
                            }
                        }
                    });
                    if (hasFields)
                    {
                        string body = EmailTemplateService.HtmlMessageBody(EmailTemplates.CMSFormPost, new { PageName = cmPage.FileName, FormFields = formData.ToString() });

                        newForm.FormHTML = body;
                        newForm.Save();
                        if (globalContact && !String.IsNullOrEmpty(Settings.GlobalContactEmailAddress))
                        {
                            MailMessage message = new MailMessage();
                            message.To.Add(Settings.GlobalContactEmailAddress);
                            message.IsBodyHtml = true;
                            message.Body       = body;
                            message.Subject    = Globals.Settings.SiteTitle + "- Form Submission From " + cmPage.FileName;
                            if (!String.IsNullOrEmpty(newForm.UploadedFile))
                            {
                                message.Attachments.Add(new Attachment(HttpContext.Current.Server.MapPath(UploadedFilesLocation + newForm.UploadedFile)));
                            }
                            SmtpClient client = new SmtpClient();
                            client.Send(message);
                        }
                        else if (!String.IsNullOrEmpty(cmPage.FormRecipient))
                        {
                            cmPage.FormRecipient.Split(',').ToList().ForEach(recipient =>
                            {
                                MailMessage message = new MailMessage();
                                message.To.Add(recipient);
                                message.IsBodyHtml = true;
                                message.Body       = body;
                                message.Subject    = Globals.Settings.SiteTitle + "- Form Submission From " + cmPage.FileName;
                                if (!String.IsNullOrEmpty(newForm.UploadedFile))
                                {
                                    message.Attachments.Add(new Attachment(HttpContext.Current.Server.MapPath(UploadedFilesLocation + newForm.UploadedFile)));
                                }
                                SmtpClient client = new SmtpClient();
                                client.Send(message);
                            });
                        }
                    }
                    if (hasFields)
                    {
                        if (globalContact)
                        {
                            Page page = (Page)HttpContext.Current.Handler;
                            page.ClientScript.RegisterStartupScript(page.GetType(), PopupScriptName, @"$(document).ready(function(){
	if ($('a#contactDummyLink').length == 0)
		$('div.contactSuccess').parent().parent().prepend('<a href=""#contactSuccess"" style=""display:none;"" id=""contactDummyLink"">success</a>');
	$('a#contactDummyLink').fancybox();
	$('a#contactDummyLink').trigger('click');
	setTimeout(function(){$.fancybox.close();}, 4000);
});", true);
                        }
                        else if (cmPage.ResponsePageID != null)
                        {
                            HttpContext.Current.Response.Redirect(CMSHelpers.GetCachedCMPages().Where(p => p.CMPageID == cmPage.ResponsePageID.Value).Single().FileName);
                        }
                        else
                        {
                            Page page = (Page)HttpContext.Current.Handler;
                            //If you change the key or type of the script below,
                            //you must also change it on the _RadEditor.cs file or your page will not load correctly
                            //in the if statement with Page.ClientScript.IsStartupScriptRegistered(Page.GetType(), "PopupScript")
                            page.ClientScript.RegisterStartupScript(page.GetType(), PopupScriptName, "alert('Thank you. Your form has been submitted successfully.');", true);
                        }
                    }
                }
            }
        }
Exemplo n.º 4
0
        public static void SendPropertyStatisticEmail(List <ShowcaseItem> properties, string emailAddresses = null, string subject = null, string message = null, bool updateHistoricalStats = true)
        {
            if (!properties.Any())
            {
                return;
            }

            string agentFirstAndLast;
            string agentImage;
            string agentOfficePhone;
            string agentFax = string.Empty;
            string agentEmail;
            string agentCellPhone = string.Empty;

            if (properties.Any(a => a.AgentID.HasValue))
            {
                Classes.Media352_MembershipProvider.User userEntity = Classes.Media352_MembershipProvider.User.GetByID(properties.FirstOrDefault(a => a.AgentID.HasValue).AgentID.Value, (new[] { "UserInfo" }).ToList());
                UserInfo userInfo = userEntity.UserInfo.FirstOrDefault();
                if (userInfo == null)
                {
                    return;
                }
                agentFirstAndLast = userInfo.FirstAndLast;
                agentImage        = userInfo.Photo;
                agentOfficePhone  = userInfo.OfficePhone;
                agentFax          = userInfo.Fax;
                agentEmail        = userEntity.Email;
                agentCellPhone    = userInfo.CellPhone;
            }
            else if (properties.Any(a => a.TeamID.HasValue))
            {
                Team teamEntity = Team.GetByID(properties.FirstOrDefault(a => a.TeamID.HasValue).TeamID.Value);
                agentFirstAndLast = teamEntity.Name;
                agentImage        = teamEntity.Photo;
                agentOfficePhone  = teamEntity.Phone;
                agentEmail        = teamEntity.Email;
            }
            else
            {
                return;
            }

            if (String.IsNullOrWhiteSpace(emailAddresses))
            {
                emailAddresses = agentEmail;
            }

            if (string.IsNullOrWhiteSpace(emailAddresses))
            {
                return;
            }

            MailMessage email = new MailMessage
            {
                IsBodyHtml = true,
                From       = new MailAddress(Globals.Settings.FromEmail)
            };

            //TODO: Remove this when done testing.  Put in place to prevent spamming of meybohm agents
            if (System.Web.HttpContext.Current.IsDebuggingEnabled && !emailAddresses.ToLower().Contains("@352media.com"))
            {
                email.To.Add("*****@*****.**");
            }
            else
            {
                foreach (string emailAddress in emailAddresses.Split(';'))
                {
                    if (Regex.IsMatch(emailAddress, Helpers.EmailValidationExpression))
                    {
                        email.To.Add(emailAddress);
                    }
                }
            }
            if (!email.To.Any())
            {
                return;
            }

            string propertyHtml     = "<ul>";
            string basePropertyHtml = EmailTemplateService.HtmlMessageBody(EmailTemplates.PropertyItemForStatistics, null, false);

            string statsTableRowTemplate = @"<tr>
				<td>Number of [[Key]]:</td>
				<td>[[Value]]</td>
			</tr>"            ;

            DateTime beginDate = DateTime.UtcNow.AddDays(-7);
            DateTime endDate   = DateTime.UtcNow;

            bool addedProperty = false;

            foreach (ShowcaseItem property in properties)
            {
                try
                {
                    Dictionary <string, int> clickCounts = GetStatisticsForProperty(property.ShowcaseItemID, beginDate, endDate, updateHistoricalStats);
                    string statsSection = string.Empty;
                    foreach (KeyValuePair <string, int> metric in clickCounts)
                    {
                        statsSection += statsTableRowTemplate.Replace("[[Key]]", metric.Key == "Visit" || metric.Key == "Share" ? metric.Key + "s" : "Clicks on " + metric.Key + " Tab")
                                        .Replace("[[Value]]", metric.Value.ToString());
                    }
                    if (!clickCounts.Any())
                    {
                        statsSection += "<tr><td colspan=\"2\">No visits this week</td></tr>";
                    }

                    string msLink = property.ShowcaseID == (int)MeybohmShowcases.AikenExistingHomes || property.ShowcaseID == (int)MeybohmShowcases.AikenRentalHomes
                                                                        ? "aiken/" : "augusta/";
                    string searchType = property.ShowcaseID == (int)MeybohmShowcases.AikenExistingHomes || property.ShowcaseID == (int)MeybohmShowcases.AugustaExistingHomes ? (property.NewHome?"new-":"") + "search" : "rentals";


                    string thisPropertyHtml = basePropertyHtml.Replace("[[Title]]", property.Title)
                                              .Replace("[[Image]]", !String.IsNullOrWhiteSpace(property.Image) && !property.Image.ToLower().StartsWith("http") ? Helpers.RootPath + Globals.Settings.UploadFolder + "images/" + property.Image : property.Image)
                                              .Replace("[[Address]]", property.Address.Address1 + "<br />" + property.Address.City + ", " + property.Address.State.Abb + " " + property.Address.Zip)
                                              .Replace("[[DateListed]]", property.DateListed.HasValue ? property.DateListed.Value.ToShortDateString() : string.Empty)
                                              .Replace("[[NumberOfPhotos]]", Media.GetNumberOfPhotos(property.ShowcaseItemID).ToString())
                                              .Replace("[[StatsFromShowcaseItemMetric]]", statsSection)
                                              .Replace("[[PropertyLink]]", Helpers.RootPath + msLink + searchType + "?id=" + property.ShowcaseItemID);

                    if (thisPropertyHtml.IndexOf("[[SavedSearchBegin]]", StringComparison.Ordinal) > 0 && thisPropertyHtml.IndexOf("[[SavedSearchEnd]]", StringComparison.Ordinal) > 0)
                    {
                        thisPropertyHtml = thisPropertyHtml.Remove(thisPropertyHtml.IndexOf("[[SavedSearchBegin]]", StringComparison.Ordinal), thisPropertyHtml.IndexOf("[[SavedSearchEnd]]", StringComparison.Ordinal) - thisPropertyHtml.IndexOf("[[SavedSearchBegin]]", StringComparison.Ordinal) + "[[SavedSearchEnd]]".Length);
                    }

                    propertyHtml += thisPropertyHtml;
                    addedProperty = true;
                }
                catch (Exception ex)
                {
                    BaseCode.Helpers.LogException(ex);
                }
            }

            if (!addedProperty)
            {
                return;
            }

            propertyHtml += "</ul>";
            string propertyStatsBody = EmailTemplateService.HtmlMessageBody(EmailTemplates.PropertyStatistics, new
            {
                PersonalMessage = message,
                SiteName        = Globals.Settings.SiteTitle,
                BeginDate       = beginDate.ToShortDateString(),
                EndDate         = endDate.ToShortDateString(),
                AgentName       = agentFirstAndLast,
                AgentImage      = !String.IsNullOrWhiteSpace(agentImage) ? (!agentImage.ToLower().StartsWith("http") ? Helpers.RootPath + Globals.Settings.UploadFolder + "agents/" + agentImage : agentImage) : Helpers.RootPath + Globals.Settings.UploadFolder + "images/missingFile.jpg",
                OfficePhone     = agentOfficePhone,
                Fax             = agentFax,
                CellPhone       = agentCellPhone,
                AgentEmail      = agentEmail,
                Properties      = propertyHtml
            });

            if (propertyStatsBody.IndexOf("[[PersonalMessageBegin]]", StringComparison.Ordinal) > 0 && propertyStatsBody.IndexOf("[[PersonalMessageEnd]]", StringComparison.Ordinal) > 0 && String.IsNullOrWhiteSpace(message))
            {
                propertyStatsBody = propertyStatsBody.Remove(propertyStatsBody.IndexOf("[[PersonalMessageBegin]]", StringComparison.Ordinal), propertyStatsBody.IndexOf("[[PersonalMessageEnd]]", StringComparison.Ordinal) - propertyStatsBody.IndexOf("[[PersonalMessageBegin]]", StringComparison.Ordinal) + "[[PersonalMessageEnd]]".Length);
            }
            else
            {
                propertyStatsBody = propertyStatsBody.Replace("[[PersonalMessageBegin]]", "").Replace("[[PersonalMessageEnd]]", "");
            }

            email.Body    = propertyStatsBody;
            email.Subject = String.IsNullOrWhiteSpace(subject) ? "Your Property Statistics from " + Globals.Settings.SiteTitle : subject;

            SmtpClient smtp = new SmtpClient();

            smtp.Send(email);
            foreach (ShowcaseItem showcaseItem in properties)
            {
                new PropertyStatisticsEmailLog {
                    ShowcaseItemID = showcaseItem.ShowcaseItemID, Email = emailAddresses, TimeSent = DateTime.UtcNow
                }.Save();
            }
        }
Exemplo n.º 5
0
        public static void SendAlertEmails(List <SavedSearch> searches, List <WhatChanged> whatChanged = null)
        {
            Classes.Media352_MembershipProvider.User userEntity = Classes.Media352_MembershipProvider.User.GetByID(searches.FirstOrDefault().UserID, (new[] { "UserInfo" }).ToList());
            string toAddress = userEntity.Email;
            string propertyLinks = string.Empty, searchLinks = string.Empty;

            string basePropertyHtml       = EmailTemplateService.HtmlMessageBody(EmailTemplates.SavedSearchProperty, null, false);
            string baseFilterHtml         = EmailTemplateService.HtmlMessageBody(EmailTemplates.SavedSearchFilter, null, false);
            string baseFilterPropertyHtml = EmailTemplateService.HtmlMessageBody(EmailTemplates.SavedSearchFilterProperty, null, false);

            foreach (SavedSearch search in searches)
            {
                string msLink = search.ShowcaseID == (int)MeybohmShowcases.AikenExistingHomes || search.ShowcaseID == (int)MeybohmShowcases.AikenRentalHomes
                                                                ? "aiken/" : "augusta/";
                string searchType = search.ShowcaseID == (int)MeybohmShowcases.AikenRentalHomes || search.ShowcaseID == (int)MeybohmShowcases.AugustaRentalHomes ? "rentals" : "search";
                if (!string.IsNullOrEmpty(search.FilterString))
                {
                    string      propertiesText    = string.Empty;
                    WhatChanged whatChangedEntity = whatChanged.Find(f => f.SavedSearch.SavedSearchID == search.SavedSearchID);
                    if (whatChangedEntity != null)
                    {
                        foreach (ShowcaseItemForJSON property in whatChangedEntity.PropertiesThatChanged)
                        {
                            string whatChangedText = string.Empty;
                            List <PropertyChangeLog> propertyChanges = whatChangedEntity.ChangeLog.Where(s => s.ShowcaseItemID == property.ShowcaseItemID && !m_ChangeLogAttributesToIgnore.Any(a => a == s.Attribute)).ToList();
                            if (propertyChanges.Any())
                            {
                                if (propertyChanges.Any(c => c.Attribute == "Home Added"))
                                {
                                    whatChangedText += "<img alt=\"Listing Updated\" src=\"[[ROOT]]img/exclamation.png\" />&nbsp; Home Added";
                                }
                                else
                                {
                                    foreach (PropertyChangeLog change in propertyChanges)
                                    {
                                        whatChangedText += "<img alt=\"Listing Updated\" src=\"[[ROOT]]img/exclamation.png\" />&nbsp; " + change.Attribute + " Updated,";
                                    }
                                }
                            }
                            else
                            {
                                whatChangedText = "<img alt=\"Listing Updated\" src=\"[[ROOT]]img/exclamation.png\" />&nbsp; Home Added";
                            }

                            propertiesText += baseFilterPropertyHtml.Replace("[[Address]]", property.Address + "<br />" + property.City + ", " + property.State + " " + property.Zipcode)
                                              .Replace("[[Title]]", property.Title.Replace(" Bedrooms:", "<br />Bedrooms:"))
                                              .Replace("[[Image]]", !String.IsNullOrWhiteSpace(property.Image) && !property.Image.ToLower().StartsWith("http") ? Helpers.RootPath + Globals.Settings.UploadFolder + "images/" + property.Image : property.Image)
                                              .Replace("[[WhatChanged]]", whatChangedText.TrimEnd(',').Replace(",", "<br />"));
                        }
                    }

                    searchLinks += baseFilterHtml.Replace("[[Url]]", Helpers.RootPath + msLink + searchType + "?" + search.FilterString)
                                   .Replace("[[Name]]", search.Name)
                                   .Replace("[[Properties]]", propertiesText);
                }

                if (search.ShowcaseItemID > 0)
                {
                    ShowcaseItem property = ShowcaseItem.GetByID((int)search.ShowcaseItemID, new string[] { "Address", "Address.State" });
                    if (!property.Active)
                    {
                        continue;
                    }
                    propertyLinks  = string.IsNullOrEmpty(propertyLinks) ? string.Format(@"<tr style=""background-color: #f5f5f5; padding: 10px 0; width: 100%;"">
	<td style=""text-align: center; padding: 10px 0; font-family: Arial, sans-serif; font-size: 16px; color: #999; line-height: 1.4; vertical-align: top;"" colspan=""2"">
		Updated Properties: &nbsp;{0}		
	</td>
</tr>
<tr>
	<td colspan=""2"">&nbsp;</td>
</tr>", string.Join(", ", searches.Where(s => s.ShowcaseItemID.HasValue).Select(s => s.Name))) : propertyLinks;
                    propertyLinks += basePropertyHtml.Replace("[[Title]]", property.Title.Replace(" Bedrooms:", "<br />Bedrooms:"))
                                     .Replace("[[Image]]", !String.IsNullOrWhiteSpace(property.Image) && !property.Image.ToLower().StartsWith("http") ? Helpers.RootPath + Globals.Settings.UploadFolder + "images/" + property.Image : property.Image)
                                     .Replace("[[Address]]", property.Address.Address1 + "<br />" + property.Address.City + ", " + property.Address.State.Abb + " " + property.Address.Zip)
                                     .Replace("[[DateListed]]", property.DateListed.HasValue ? property.DateListed.Value.ToShortDateString() : string.Empty)
                                     .Replace("[[NumberOfPhotos]]", Media.GetNumberOfPhotos(property.ShowcaseItemID).ToString())
                                     .Replace("[[WhatChanged]]", "<img alt=\"Listing Updated\" src=\"[[ROOT]]img/exclamation.png\" />&nbsp; " + PropertyChangeLog.PropertyChangeLogPage(0, 1, "", "DateStamp", false, new PropertyChangeLog.Filters {
                        FilterPropertyChangeLogShowcaseItemID = search.ShowcaseItemID.ToString()
                    }).FirstOrDefault().Attribute.Replace("PhotoURL", "Photos") + " Updated")
                                     .Replace("[[PropertyLink]]", Helpers.RootPath + msLink + searchType + "?id=" + property.ShowcaseItemID);
                }
            }

            UserInfo userInfo = userEntity.UserInfo.FirstOrDefault();

            if (string.IsNullOrWhiteSpace(toAddress) || userInfo == null || (string.IsNullOrEmpty(propertyLinks) && string.IsNullOrEmpty(searchLinks)))
            {
                return;
            }
            MailMessage email = new MailMessage
            {
                IsBodyHtml = true,
                From       = new MailAddress(Globals.Settings.FromEmail)
            };

            email.To.Add(toAddress);
            email.Body = EmailTemplateService.HtmlMessageBody(EmailTemplates.SavedSearch, new
            {
                FirstAndLastName = userInfo.FirstAndLast,
                PropertyLinks    = propertyLinks,
                SearchLinks      = searchLinks
            });
            email.Subject = Globals.Settings.SiteTitle + " - Saved Search";

            SmtpClient smtp = new SmtpClient();

            smtp.Send(email);
        }
Exemplo n.º 6
0
        public static void SendSubmissionEmail(Contact contactEntity, ContactTypes contactFormType)
        {
            string       toAddress    = contactFormType == ContactTypes.ContactUs ? Settings.ContactSubmissionEmailAddress : contactFormType == ContactTypes.HomeValuationRequest ? Settings.HomeValuationEmailAddress : Settings.MaintenanceRequestEmailAddress;
            string       templatePath = contactFormType == ContactTypes.ContactUs ? EmailTemplates.ContactSubmission : contactFormType == ContactTypes.HomeValuationRequest ? EmailTemplates.HomeValuation : EmailTemplates.MaintenanceRequest;
            string       propertyInfo = string.Empty;
            string       microsite    = string.Empty;
            ShowcaseItem showcaseItem = null;

            if (contactEntity.ShowcaseItemID.HasValue)
            {
                showcaseItem = Classes.Showcase.ShowcaseItem.GetByID(contactEntity.ShowcaseItemID.Value, new string[] { "Agent", "Showcase.CMMicrosite", "Team", "Address" });
                if (showcaseItem.AgentID.HasValue)
                {
                    toAddress = showcaseItem.Agent.Email;
                }
                else if (showcaseItem.TeamID.HasValue)
                {
                    toAddress = showcaseItem.Team.Email;
                }
                else
                {
                    toAddress = Classes.Contacts.Settings.DefaultAgentContactEmail;
                }
                templatePath = EmailTemplates.PropertyInfoRequest;
                propertyInfo = showcaseItem.Address.FormattedAddress + (showcaseItem.MlsID.HasValue ? "<br />MLS ID #" + showcaseItem.MlsID : "");
                microsite    = showcaseItem.Showcase.CMMicrosite.Name.ToLower().Replace(" ", "-");
            }
            else if (contactEntity.AgentID.HasValue)
            {
                Classes.Media352_MembershipProvider.User agent = Classes.Media352_MembershipProvider.User.GetByID(contactEntity.AgentID.Value, new[] { "UserOffice.Office" });
                if (agent.UserOffice != null && agent.UserOffice.Any(o => o.Office != null && o.Office.Active))
                {
                    toAddress = agent.Email;
                }
                else
                {
                    toAddress = Classes.Contacts.Settings.DefaultAgentContactEmail;
                }
                templatePath = EmailTemplates.ContactAgentSubmission;
            }
            else if (contactEntity.TeamID.HasValue)
            {
                Classes.Media352_MembershipProvider.Team team = Classes.Media352_MembershipProvider.Team.GetByID(contactEntity.TeamID.Value);
                toAddress    = team.Email;
                templatePath = EmailTemplates.ContactAgentSubmission;
            }

            if (string.IsNullOrWhiteSpace(toAddress))
            {
                return;
            }
            string      contactMethodName = ContactMethod.GetByID(contactEntity.ContactMethodID).Name;
            MailMessage email             = new MailMessage();

            email.IsBodyHtml = true;
            email.From       = new MailAddress(Globals.Settings.FromEmail);
            //TODO: Remove this when done testing.  Put in place to prevent spamming of meybohm agents
            if (System.Web.HttpContext.Current.IsDebuggingEnabled && toAddress.ToLower().EndsWith("@meybohm.com"))
            {
                toAddress = "*****@*****.**";
            }
            email.To.Add(toAddress);
            if (contactFormType == ContactTypes.PropertyInformation && toAddress != Settings.PropertyInfoCCEmailAddress)
            {
                email.CC.Add(Settings.PropertyInfoCCEmailAddress);
            }
            else if (contactFormType == ContactTypes.Agent && toAddress != Settings.AgentContactCCEmailAddress)
            {
                email.CC.Add(Settings.AgentContactCCEmailAddress);
            }

            Classes.StateAndCountry.Address addressEntity = null;
            if (contactEntity.AddressID.HasValue)
            {
                addressEntity = Classes.StateAndCountry.Address.GetByID(contactEntity.AddressID.Value, new string[] { "State" });
            }
            email.Body = EmailTemplateService.HtmlMessageBody(templatePath, new
            {
                FirstName     = contactEntity.FirstName,
                LastName      = contactEntity.LastName,
                Address1      = (addressEntity != null ? addressEntity.Address1 : string.Empty),
                Address2      = (addressEntity != null ? addressEntity.Address2 : string.Empty),
                City          = (addressEntity != null ? addressEntity.City : string.Empty),
                State         = (addressEntity != null ? addressEntity.State.Name : string.Empty),
                Zip           = (addressEntity != null ? addressEntity.Zip : string.Empty),
                Message       = contactEntity.Message,
                ContactMethod = contactMethodName,
                Email         = contactEntity.Email,
                PhoneOrEmail  = (contactEntity.ContactMethodID == (int)ContactMethods.Email ?"": "Phone: " + contactEntity.Phone),
                ContactTime   = ContactTime.GetByID(contactEntity.ContactTimeID).Name,
                PropertyInfo  = propertyInfo,
                Microsite     = microsite
            });
            string subjectText = contactEntity.ShowcaseItemID.HasValue ? "Property Information Request" : contactFormType == ContactTypes.ContactUs ? "Contact Form Submission" : contactFormType == ContactTypes.HomeValuationRequest ? "Home Valuation Request" : contactFormType == ContactTypes.MaintenanceRequest ? "Maintenance Request" : "Contact Agent Submission";

            if (showcaseItem != null)
            {
                if (showcaseItem.ShowcaseID == (int)MeybohmShowcases.AugustaRentalHomes || showcaseItem.ShowcaseID == (int)MeybohmShowcases.AikenRentalHomes)
                {
                    subjectText += " - Lease";
                }
            }
            email.Subject = Globals.Settings.SiteTitle + " - " + subjectText;

            // Apply MLS ID and address information to the subject line if this is a property information
            // request.
            if (showcaseItem != null && (showcaseItem.MlsID != null || showcaseItem.Address != null))
            {
                string subjectDetails = "[";

                if (showcaseItem.MlsID != null)
                {
                    subjectDetails += showcaseItem.MlsID;
                }

                if (showcaseItem.MlsID != null && showcaseItem.Address != null)
                {
                    subjectDetails += " - ";
                }

                if (showcaseItem.Address != null)
                {
                    subjectDetails += showcaseItem.Address.Address1;
                }

                subjectDetails += "] Property Information Request";

                if (showcaseItem.ShowcaseID == (int)MeybohmShowcases.AugustaRentalHomes || showcaseItem.ShowcaseID == (int)MeybohmShowcases.AikenRentalHomes)
                {
                    subjectDetails += " - Lease";
                }

                email.Subject = subjectDetails;
            }

            SmtpClient smtp = new SmtpClient();

            smtp.Send(email);
        }