Пример #1
0
        public static void Send(string fromEmail, string fromName, string subject, List <string> recipients, string message, string appRoot = "", string themeRoot = "", List <Attachment> attachments = null, bool createCommunicationHistory = true)
        {
            var errorMessages = new List <string>();

            var emailMessage = new RockEmailMessage();

            emailMessage.FromEmail = fromEmail;
            emailMessage.FromName  = fromName;
            emailMessage.Subject   = subject;
            emailMessage.SetRecipients(recipients);
            emailMessage.Message   = message;
            emailMessage.ThemeRoot = themeRoot;
            emailMessage.AppRoot   = appRoot;
            emailMessage.CreateCommunicationRecord = createCommunicationHistory;

            if (attachments != null)
            {
                foreach (var attachment in attachments)
                {
                    var binaryFile = new BinaryFile();
                    binaryFile.ContentStream = attachment.ContentStream;
                    binaryFile.FileName      = attachment.Name;
                    emailMessage.Attachments.Add(binaryFile);
                }
            }

            emailMessage.Send(out errorMessages);
        }
Пример #2
0
        private string GetFromName(RockEmailMessage emailMessage, Dictionary <string, object> mergeFields, GlobalAttributesCache globalAttributes)
        {
            string fromName = emailMessage.FromName.ResolveMergeFields(mergeFields, emailMessage.CurrentPerson, emailMessage.EnabledLavaCommands);

            fromName = fromName.IsNullOrWhiteSpace() ? globalAttributes.GetValue("OrganizationName") : fromName;
            return(fromName);
        }
Пример #3
0
        private RockEmailMessage GetTemplateRockEmailMessage(RockMessage rockMessage, Dictionary <string, object> mergeFields, GlobalAttributesCache globalAttributes)
        {
            var templateRockEmailMessage = new RockEmailMessage();

            var emailMessage = rockMessage as RockEmailMessage;

            if (emailMessage == null)
            {
                return(null);
            }

            templateRockEmailMessage.AppRoot             = emailMessage.AppRoot;
            templateRockEmailMessage.CurrentPerson       = emailMessage.CurrentPerson;
            templateRockEmailMessage.EnabledLavaCommands = emailMessage.EnabledLavaCommands;
            templateRockEmailMessage.CssInliningEnabled  = emailMessage.CssInliningEnabled;
            templateRockEmailMessage.ReplyToEmail        = emailMessage.ReplyToEmail;

            var fromAddress = GetFromAddress(emailMessage, mergeFields, globalAttributes);
            var fromName    = GetFromName(emailMessage, mergeFields, globalAttributes);

            if (fromAddress.IsNullOrWhiteSpace())
            {
                return(null);
            }

            templateRockEmailMessage.FromEmail = fromAddress;
            templateRockEmailMessage.FromName  = fromName;

            // CC
            templateRockEmailMessage.CCEmails = emailMessage.CCEmails;

            // BCC
            templateRockEmailMessage.BCCEmails = emailMessage.BCCEmails;

            templateRockEmailMessage.Subject          = emailMessage.Subject;
            templateRockEmailMessage.Message          = emailMessage.Message;
            templateRockEmailMessage.PlainTextMessage = emailMessage.PlainTextMessage;

            // Attachments
            if (emailMessage.Attachments.Any())
            {
                using (var rockContext = new RockContext())
                {
                    var binaryFileService = new BinaryFileService(rockContext);
                    foreach (var binaryFileId in emailMessage.Attachments.Where(a => a != null).Select(a => a.Id))
                    {
                        var attachment = binaryFileService.Get(binaryFileId);
                        // We need to call content stream to make sure it is loaded while we have the rock context.
                        var attachmentString = attachment.ContentStream;
                        templateRockEmailMessage.Attachments.Add(attachment);
                    }
                }
            }

            // Communication record for tracking opens & clicks
            templateRockEmailMessage.MessageMetaData = emailMessage.MessageMetaData;

            return(templateRockEmailMessage);
        }
Пример #4
0
        private string GetFromAddress(RockEmailMessage emailMessage, Dictionary <string, object> mergeFields, GlobalAttributesCache globalAttributes)
        {
            // Resolve any possible merge fields in the from address
            string fromAddress = emailMessage.FromEmail.ResolveMergeFields(mergeFields, emailMessage.CurrentPerson, emailMessage.EnabledLavaCommands);

            fromAddress = fromAddress.IsNullOrWhiteSpace() ? globalAttributes.GetValue("OrganizationEmail") : fromAddress;
            return(fromAddress);
        }
Пример #5
0
        public static void Send(Guid emailTemplateGuid, List <RecipientData> recipients, string appRoot = "", string themeRoot = "", bool createCommunicationHistory = true)
        {
            using (var rockContext = new RockContext())
            {
                var template = new SystemEmailService(rockContext).Get(emailTemplateGuid);
                if (template != null)
                {
                    var errorMessages = new List <string>();

                    var message = new RockEmailMessage(template);
                    message.SetRecipients(recipients);
                    message.ThemeRoot = themeRoot;
                    message.AppRoot   = appRoot;
                    message.CreateCommunicationRecord = createCommunicationHistory;
                    message.Send(out errorMessages);
                }
            }
        }
Пример #6
0
        private RockEmailMessage GetTemplateRockEmailMessage(Model.Communication communication, Dictionary <string, object> mergeFields, GlobalAttributesCache globalAttributes)
        {
            var resultEmailMessage = new RockEmailMessage();

            var publicAppRoot      = globalAttributes.GetValue("PublicApplicationRoot").EnsureTrailingForwardslash();
            var cssInliningEnabled = communication.CommunicationTemplate?.CssInliningEnabled ?? false;

            resultEmailMessage.AppRoot             = publicAppRoot;
            resultEmailMessage.CssInliningEnabled  = cssInliningEnabled;
            resultEmailMessage.CurrentPerson       = communication.CreatedByPersonAlias?.Person;
            resultEmailMessage.EnabledLavaCommands = communication.EnabledLavaCommands;
            resultEmailMessage.FromEmail           = communication.FromEmail;
            resultEmailMessage.FromName            = communication.FromName;

            var fromAddress = GetFromAddress(resultEmailMessage, mergeFields, globalAttributes);
            var fromName    = GetFromName(resultEmailMessage, mergeFields, globalAttributes);

            resultEmailMessage.FromEmail = fromAddress;
            resultEmailMessage.FromName  = fromName;

            // Reply To
            var replyToEmail = "";

            if (communication.ReplyToEmail.IsNotNullOrWhiteSpace())
            {
                // Resolve any possible merge fields in the replyTo address
                replyToEmail = communication.ReplyToEmail.ResolveMergeFields(mergeFields, resultEmailMessage.CurrentPerson);
            }
            resultEmailMessage.ReplyToEmail = replyToEmail;

            // Attachments
            resultEmailMessage.Attachments = communication.GetAttachments(CommunicationType.Email).Select(a => a.BinaryFile).ToList();
            // Load up the content stream while the context is still active.
            for (int i = 0; i < resultEmailMessage.Attachments.Count; i++)
            {
                var _ = resultEmailMessage.Attachments[i].ContentStream;
            }

            return(resultEmailMessage);
        }
Пример #7
0
        private static CreateMessageResult CreateEmailMessage(Person person, Dictionary <string, object> mergeObjects, SystemCommunication systemCommunication)
        {
            var createMessageResult = new CreateMessageResult();

            if (string.IsNullOrWhiteSpace(person.Email))
            {
                var warning = $"{person.FullName} does not have an email address entered.";
                createMessageResult.Warnings.Add(warning);
                RockLogger.Log.Warning(RockLogDomains.Jobs, warning);
                return(createMessageResult);
            }

            if (!person.IsEmailActive)
            {
                var warning = $"{person.FullName.ToPossessive()} email address is inactive.";
                createMessageResult.Warnings.Add(warning);
                RockLogger.Log.Warning(RockLogDomains.Jobs, warning);
                return(createMessageResult);
            }

            if (person.EmailPreference == EmailPreference.DoNotEmail)
            {
                var warning = $"{person.FullName} is marked as do not email.";
                createMessageResult.Warnings.Add(warning);
                RockLogger.Log.Warning(RockLogDomains.Jobs, warning);
                return(createMessageResult);
            }

            var recipients = new List <RockMessageRecipient>
            {
                new RockEmailMessageRecipient(person, mergeObjects)
            };

            var message = new RockEmailMessage(systemCommunication);

            message.SetRecipients(recipients);
            createMessageResult.Message = message;
            return(createMessageResult);
        }
Пример #8
0
        /// <summary>
        /// Notifies the admins.
        /// </summary>
        /// <param name="subject">The subject.</param>
        /// <param name="message">The message.</param>
        /// <param name="appRoot">The application root.</param>
        /// <param name="themeRoot">The theme root.</param>
        /// <param name="createCommunicationHistory">if set to <c>true</c> [create communication history].</param>
        /// <exception cref="System.Exception">Error sending System Email: Could not read Email Medium Entity Type</exception>
        public static void NotifyAdmins(string subject, string message, string appRoot = "", string themeRoot = "", bool createCommunicationHistory = true)
        {
            try
            {
                List <Person> personList = null;

                Guid adminGroup = Rock.SystemGuid.Group.GROUP_ADMINISTRATORS.AsGuid();

                using (var rockContext = new RockContext())
                {
                    personList = new GroupMemberService(rockContext).Queryable()
                                 .Where(m =>
                                        m.Group.Guid.Equals(adminGroup) &&
                                        m.GroupMemberStatus == GroupMemberStatus.Active &&
                                        m.Person.Email != null &&
                                        m.Person.Email != "")
                                 .Select(m => m.Person)
                                 .ToList();
                }

                var errorMessages = new List <string>();

                var recipients = personList.Select(a => new RockEmailMessageRecipient(a, null)).ToList();

                var emailMessage = new RockEmailMessage();
                emailMessage.FromEmail = GlobalAttributesCache.Value("OrganizationEmail");
                emailMessage.Subject   = subject;
                emailMessage.SetRecipients(recipients);
                emailMessage.Message   = message;
                emailMessage.ThemeRoot = themeRoot;
                emailMessage.AppRoot   = appRoot;
                emailMessage.CreateCommunicationRecord = createCommunicationHistory;
                emailMessage.Send(out errorMessages);
            }
            catch (Exception ex)
            {
                ExceptionLogService.LogException(ex, HttpContext.Current);
            }
        }
Пример #9
0
        private string GetRecipientReplyToAddress(RockEmailMessage emailMessage, Dictionary <string, object> mergeFields, SafeSenderResult safeSenderResult)
        {
            var replyToAddress = string.Empty;

            if (emailMessage.ReplyToEmail.IsNotNullOrWhiteSpace())
            {
                replyToAddress = emailMessage.ReplyToEmail.ResolveMergeFields(mergeFields, emailMessage.CurrentPerson, emailMessage.EnabledLavaCommands);
            }

            if (safeSenderResult.IsUnsafeDomain && safeSenderResult.ReplyToAddress != null)
            {
                if (replyToAddress.IsNullOrWhiteSpace())
                {
                    replyToAddress = safeSenderResult.ReplyToAddress.ToString();
                }
                else
                {
                    replyToAddress += $",{safeSenderResult.ReplyToAddress.ToString()}";
                }
            }
            return(replyToAddress);
        }
Пример #10
0
        private RockEmailMessage GetRecipientRockEmailMessage(RockEmailMessage emailMessage, Model.Communication communication, CommunicationRecipient communicationRecipient, Dictionary <string, object> mergeFields, string organizationEmail, Dictionary <string, string> mediumAttributes)
        {
            var recipientEmail = new RockEmailMessage();

            recipientEmail.CurrentPerson       = emailMessage.CurrentPerson;
            recipientEmail.EnabledLavaCommands = emailMessage.EnabledLavaCommands;
            recipientEmail.AppRoot             = emailMessage.AppRoot;
            recipientEmail.CssInliningEnabled  = emailMessage.CssInliningEnabled;

            // CC
            if (communication.CCEmails.IsNotNullOrWhiteSpace())
            {
                string[] ccRecipients = communication
                                        .CCEmails
                                        .ResolveMergeFields(mergeFields, emailMessage.CurrentPerson)
                                        .Replace(";", ",")
                                        .Split(',');

                foreach (var ccRecipient in ccRecipients)
                {
                    recipientEmail.CCEmails.Add(ccRecipient);
                }
            }

            // BCC
            if (communication.BCCEmails.IsNotNullOrWhiteSpace())
            {
                string[] bccRecipients = communication
                                         .BCCEmails
                                         .ResolveMergeFields(mergeFields, emailMessage.CurrentPerson)
                                         .Replace(";", ",")
                                         .Split(',');

                foreach (var bccRecipient in bccRecipients)
                {
                    recipientEmail.BCCEmails.Add(bccRecipient);
                }
            }

            // Attachments
            recipientEmail.Attachments = emailMessage.Attachments;

            // Communication record for tracking opens & clicks
            recipientEmail.MessageMetaData = new Dictionary <string, string>(emailMessage.MessageMetaData);

            // To
            var toEmailAddress = new RockEmailMessageRecipient(null, null)
            {
                To   = communicationRecipient.PersonAlias.Person.Email,
                Name = communicationRecipient.PersonAlias.Person.FullName
            };

            recipientEmail.SetRecipients(new List <RockEmailMessageRecipient> {
                toEmailAddress
            });

            var fromMailAddress = new MailAddress(emailMessage.FromEmail, emailMessage.FromName);
            var checkResult     = CheckSafeSender(new List <string> {
                toEmailAddress.EmailAddress
            }, fromMailAddress, organizationEmail);

            // Reply To
            recipientEmail.ReplyToEmail = GetRecipientReplyToAddress(emailMessage, mergeFields, checkResult);

            // From
            if (checkResult.IsUnsafeDomain && checkResult.SafeFromAddress != null)
            {
                recipientEmail.FromName  = checkResult.SafeFromAddress.DisplayName;
                recipientEmail.FromEmail = checkResult.SafeFromAddress.Address;
            }
            else
            {
                recipientEmail.FromName  = fromMailAddress.DisplayName;
                recipientEmail.FromEmail = fromMailAddress.Address;
            }

            // Subject
            var subject = ResolveText(communication.Subject, emailMessage.CurrentPerson, communication.EnabledLavaCommands, mergeFields, emailMessage.AppRoot);

            recipientEmail.Subject = subject;

            // Body Plain Text
            if (mediumAttributes.ContainsKey("DefaultPlainText"))
            {
                var plainText = ResolveText(mediumAttributes["DefaultPlainText"],
                                            emailMessage.CurrentPerson,
                                            communication.EnabledLavaCommands,
                                            mergeFields,
                                            emailMessage.AppRoot);

                if (!string.IsNullOrWhiteSpace(plainText))
                {
                    recipientEmail.PlainTextMessage = plainText;
                }
            }

            // Body (HTML)
            string htmlBody = communication.Message;

            // Get the unsubscribe content and add a merge field for it
            if (communication.IsBulkCommunication && mediumAttributes.ContainsKey("UnsubscribeHTML"))
            {
                string unsubscribeHtml = ResolveText(mediumAttributes["UnsubscribeHTML"],
                                                     emailMessage.CurrentPerson,
                                                     communication.EnabledLavaCommands,
                                                     mergeFields,
                                                     emailMessage.AppRoot);

                mergeFields.AddOrReplace("UnsubscribeOption", unsubscribeHtml);

                htmlBody = ResolveText(htmlBody, emailMessage.CurrentPerson, communication.EnabledLavaCommands, mergeFields, emailMessage.AppRoot);

                // Resolve special syntax needed if option was included in global attribute
                if (Regex.IsMatch(htmlBody, @"\[\[\s*UnsubscribeOption\s*\]\]"))
                {
                    htmlBody = Regex.Replace(htmlBody, @"\[\[\s*UnsubscribeOption\s*\]\]", unsubscribeHtml);
                }

                // Add the unsubscribe option at end if it wasn't included in content
                if (!htmlBody.Contains(unsubscribeHtml))
                {
                    htmlBody += unsubscribeHtml;
                }
            }
            else
            {
                htmlBody = ResolveText(htmlBody, emailMessage.CurrentPerson, communication.EnabledLavaCommands, mergeFields, emailMessage.AppRoot);
                htmlBody = Regex.Replace(htmlBody, @"\[\[\s*UnsubscribeOption\s*\]\]", string.Empty);
            }

            if (!string.IsNullOrWhiteSpace(htmlBody))
            {
                if (emailMessage.CssInliningEnabled)
                {
                    // move styles inline to help it be compatible with more email clients
                    htmlBody = htmlBody.ConvertHtmlStylesToInlineAttributes();
                }

                // add the main Html content to the email
                recipientEmail.Message = htmlBody;
            }

            recipientEmail.MessageMetaData["communication_recipient_guid"] = communicationRecipient.Guid.ToString();

            return(recipientEmail);
        }
Пример #11
0
        private RockEmailMessage GetRecipientRockEmailMessage(RockEmailMessage emailMessage, RockMessageRecipient rockMessageRecipient, Dictionary <string, object> mergeFields, string organizationEmail)
        {
            var recipientEmail = new RockEmailMessage();

            recipientEmail.CurrentPerson       = emailMessage.CurrentPerson;
            recipientEmail.EnabledLavaCommands = emailMessage.EnabledLavaCommands;
            recipientEmail.AppRoot             = emailMessage.AppRoot;
            recipientEmail.CssInliningEnabled  = emailMessage.CssInliningEnabled;
            // CC
            recipientEmail.CCEmails = emailMessage.CCEmails;

            // BCC
            recipientEmail.BCCEmails = emailMessage.BCCEmails;


            // Attachments
            recipientEmail.Attachments = emailMessage.Attachments;

            // Communication record for tracking opens & clicks
            recipientEmail.MessageMetaData = new Dictionary <string, string>(emailMessage.MessageMetaData);

            foreach (var mergeField in mergeFields)
            {
                rockMessageRecipient.MergeFields.AddOrIgnore(mergeField.Key, mergeField.Value);
            }

            // To
            var toEmailAddress = new RockEmailMessageRecipient(null, null)
            {
                To = rockMessageRecipient
                     .To
                     .ResolveMergeFields(rockMessageRecipient.MergeFields, emailMessage.CurrentPerson, emailMessage.EnabledLavaCommands),
                Name = rockMessageRecipient
                       .Name
                       .ResolveMergeFields(rockMessageRecipient.MergeFields, emailMessage.CurrentPerson, emailMessage.EnabledLavaCommands)
            };

            recipientEmail.SetRecipients(new List <RockEmailMessageRecipient> {
                toEmailAddress
            });

            var fromMailAddress = new MailAddress(emailMessage.FromEmail, emailMessage.FromName);
            var checkResult     = CheckSafeSender(new List <string> {
                toEmailAddress.EmailAddress
            }, fromMailAddress, organizationEmail);

            // Reply To
            recipientEmail.ReplyToEmail = GetRecipientReplyToAddress(emailMessage, mergeFields, checkResult);

            // From
            if (checkResult.IsUnsafeDomain && checkResult.SafeFromAddress != null)
            {
                recipientEmail.FromName  = checkResult.SafeFromAddress.DisplayName;
                recipientEmail.FromEmail = checkResult.SafeFromAddress.Address;
            }
            else
            {
                recipientEmail.FromName  = fromMailAddress.DisplayName;
                recipientEmail.FromEmail = fromMailAddress.Address;
            }

            // Subject
            string subject = ResolveText(emailMessage.Subject, emailMessage.CurrentPerson, emailMessage.EnabledLavaCommands, rockMessageRecipient.MergeFields, emailMessage.AppRoot, emailMessage.ThemeRoot).Left(998);

            recipientEmail.Subject = subject;

            // Plain Text Message
            recipientEmail.PlainTextMessage = ResolveText(emailMessage.PlainTextMessage, emailMessage.CurrentPerson, emailMessage.EnabledLavaCommands, rockMessageRecipient.MergeFields, emailMessage.AppRoot, emailMessage.ThemeRoot);

            // Body (HTML)
            string body = ResolveText(emailMessage.Message, emailMessage.CurrentPerson, emailMessage.EnabledLavaCommands, rockMessageRecipient.MergeFields, emailMessage.AppRoot, emailMessage.ThemeRoot);

            body = Regex.Replace(body, @"\[\[\s*UnsubscribeOption\s*\]\]", string.Empty);
            recipientEmail.Message = body;


            Guid?recipientGuid = null;

            recipientEmail.CreateCommunicationRecord = emailMessage.CreateCommunicationRecord;
            if (emailMessage.CreateCommunicationRecord)
            {
                recipientGuid = Guid.NewGuid();
                recipientEmail.MessageMetaData["communication_recipient_guid"] = recipientGuid.ToString();
            }

            return(recipientEmail);
        }
Пример #12
0
 /// <summary>
 /// Send the implementation specific email. This class will call this method and pass the post processed data in a  rock email message which
 /// can then be used to send the implementation specific message.
 /// </summary>
 /// <param name="rockEmailMessage">The rock email message.</param>
 /// <returns></returns>
 protected abstract EmailSendResponse SendEmail(RockEmailMessage rockEmailMessage);