private void Send(string recipients, string from, string subject, string body, Dictionary <string, object> mergeFields, RockContext rockContext, bool createCommunicationRecord, Dictionary <string, string> metaData) { var recipientList = recipients.SplitDelimitedValues().ToList(); var mediumData = new Dictionary <string, string>(); mediumData.Add("From", from.ResolveMergeFields(mergeFields)); mediumData.Add("Subject", subject.ResolveMergeFields(mergeFields)); mediumData.Add("Body", System.Text.RegularExpressions.Regex.Replace(body.ResolveMergeFields(mergeFields), @"\[\[\s*UnsubscribeOption\s*\]\]", string.Empty)); var mediumEntity = EntityTypeCache.Read(Rock.SystemGuid.EntityType.COMMUNICATION_MEDIUM_EMAIL.AsGuid(), rockContext); if (mediumEntity != null) { var medium = MediumContainer.GetComponent(mediumEntity.Name); if (medium != null && medium.IsActive) { var transport = medium.Transport; if (transport != null && transport.IsActive) { var appRoot = GlobalAttributesCache.Read(rockContext).GetValue("InternalApplicationRoot"); if (transport is Rock.Communication.Transport.SMTPComponent) { ((Rock.Communication.Transport.SMTPComponent)transport).Send(mediumData, recipientList, appRoot, string.Empty, createCommunicationRecord, metaData); } else { transport.Send(mediumData, recipientList, appRoot, string.Empty); } } } } }
private void SendEmail(string recipient, string from, string subject, string body, RockContext rockContext) { var recipients = new List <string>(); recipients.Add(recipient); var mediumData = new Dictionary <string, string>(); mediumData.Add("From", from); mediumData.Add("Subject", subject); mediumData.Add("Body", body); var mediumEntity = EntityTypeCache.Read(Rock.SystemGuid.EntityType.COMMUNICATION_MEDIUM_EMAIL.AsGuid(), rockContext); if (mediumEntity != null) { var medium = MediumContainer.GetComponent(mediumEntity.Name); if (medium != null && medium.IsActive) { var transport = medium.Transport; if (transport != null && transport.IsActive) { var appRoot = GlobalAttributesCache.Read(rockContext).GetValue("InternalApplicationRoot"); transport.Send(mediumData, recipients, appRoot, string.Empty); } } } }
/// <summary> /// Shows the detail. /// </summary> private void ShowDetail() { Rock.Model.Communication communication = null; if (CommunicationId.HasValue) { communication = new CommunicationService(new RockContext()) .Queryable("CreatedByPersonAlias.Person") .Where(c => c.Id == CommunicationId.Value) .FirstOrDefault(); } // If not valid for this block, hide contents and return if (communication == null || communication.Status == CommunicationStatus.Transient || communication.Status == CommunicationStatus.Draft) { // If viewing a new, transient or draft communication, hide this block and use NewCommunication block this.Visible = false; return; } ShowStatus(communication); lTitle.Text = (communication.Subject ?? "Communication").FormatAsHtmlTitle(); SetPersonDateValue(lCreatedBy, communication.CreatedByPersonAlias, communication.CreatedDateTime, "Created By"); SetPersonDateValue(lApprovedBy, communication.ReviewerPersonAlias, communication.ReviewedDateTime, "Approved By"); if (communication.FutureSendDateTime.HasValue && communication.FutureSendDateTime.Value > RockDateTime.Now) { lFutureSend.Text = String.Format("<div class='alert alert-success'><strong>Future Send</strong> This communication is scheduled to be sent {0} <small>({1})</small>.</div>", communication.FutureSendDateTime.Value.ToRelativeDateString(), communication.FutureSendDateTime.Value.ToString()); } pnlOpened.Visible = false; lDetails.Text = communication.MediumDataJson; if (communication.MediumEntityTypeId.HasValue) { var mediumEntityType = EntityTypeCache.Read(communication.MediumEntityTypeId.Value); if (mediumEntityType != null) { var medium = MediumContainer.GetComponent(mediumEntityType.Name); if (medium != null) { pnlOpened.Visible = medium.Transport.CanTrackOpens; lDetails.Text = medium.GetMessageDetails(communication); } } } BindRecipients(); BindActivity(); ShowActions(communication); }
/// <summary> /// Executes the specified context. /// </summary> /// <param name="context">The context.</param> public virtual void Execute(IJobExecutionContext context) { var rockContext = new RockContext(); var dataMap = context.JobDetail.JobDataMap; var groupType = GroupTypeCache.Get(dataMap.GetString(AttributeKey.GroupType).AsGuid()); var isGroupTypeValid = groupType.TakesAttendance && groupType.SendAttendanceReminder; var results = new StringBuilder(); context.Result = "0 attendance reminders sent."; if (!isGroupTypeValid) { var warning = $"Group Type {groupType.Name} isn't setup to take attendance or send attendance reminders."; results.Append(FormatWarningMessage(warning)); RockLogger.Log.Warning(RockLogDomains.Jobs, warning); context.Result = results.ToString(); throw new RockJobWarningException(warning); } var systemEmailGuid = dataMap.GetString(AttributeKey.SystemEmail).AsGuid(); var systemCommunication = new SystemCommunicationService(rockContext).Get(systemEmailGuid); var jobPreferredCommunicationType = ( CommunicationType )dataMap.GetString(AttributeKey.SendUsingConfiguration).AsInteger(); var isSmsEnabled = MediumContainer.HasActiveSmsTransport() && !string.IsNullOrWhiteSpace(systemCommunication.SMSMessage); if (jobPreferredCommunicationType == CommunicationType.SMS && !isSmsEnabled) { // If sms selected but not usable default to email. var errorMessage = $"The job is setup to send via SMS but either SMS isn't enabled or no SMS message was found in system communication {systemCommunication.Title}."; HandleErrorMessage(context, errorMessage); } if (jobPreferredCommunicationType != CommunicationType.Email && string.IsNullOrWhiteSpace(systemCommunication.SMSMessage)) { var warning = $"No SMS message found in system communication {systemCommunication.Title}. All attendance reminders were sent via email."; results.Append(FormatWarningMessage(warning)); RockLogger.Log.Warning(RockLogDomains.Jobs, warning); jobPreferredCommunicationType = CommunicationType.Email; } var occurrences = GetOccurenceDates(groupType, dataMap, rockContext); var groupIds = occurrences.Where(o => o.Value.Any()).Select(o => o.Key).ToList(); var leaders = GetGroupLeaders(groupIds, rockContext); var attendanceRemindersResults = SendAttendanceReminders(leaders, occurrences, systemCommunication, jobPreferredCommunicationType, isSmsEnabled); results.AppendLine($"{attendanceRemindersResults.MessagesSent} attendance reminders sent."); results.Append(FormatWarningMessages(attendanceRemindersResults.Warnings)); context.Result = results.ToString(); HandleErrorMessages(context, attendanceRemindersResults.Errors); }
/// <summary> /// Shows the detail. /// </summary> private void ShowDetail(Rock.Model.Communication communication) { ShowStatus(communication); lTitle.Text = (communication.Subject ?? "Communication").FormatAsHtmlTitle(); pdAuditDetails.SetEntity(communication, ResolveRockUrl("~")); SetPersonDateValue(lCreatedBy, communication.CreatedByPersonAlias, communication.CreatedDateTime, "Created By"); SetPersonDateValue(lApprovedBy, communication.ReviewerPersonAlias, communication.ReviewedDateTime, "Approved By"); if (communication.FutureSendDateTime.HasValue && communication.FutureSendDateTime.Value > RockDateTime.Now) { lFutureSend.Text = String.Format("<div class='alert alert-success'><strong>Future Send</strong> This communication is scheduled to be sent {0} <small>({1})</small>.</div>", communication.FutureSendDateTime.Value.ToRelativeDateString(), communication.FutureSendDateTime.Value.ToString()); } pnlOpened.Visible = false; lDetails.Text = communication.MediumDataJson; if (communication.MediumEntityTypeId.HasValue) { var mediumEntityType = EntityTypeCache.Read(communication.MediumEntityTypeId.Value); if (mediumEntityType != null) { var medium = MediumContainer.GetComponent(mediumEntityType.Name); if (medium != null && medium.Transport != null) { pnlOpened.Visible = medium.Transport.CanTrackOpens; lDetails.Text = medium.GetMessageDetails(communication); } } } if (communication.MediumData != null && communication.MediumData.ContainsKey("UrlReferrer")) { lDetails.Text += string.Format("<small>Originated from <a href='{0}'>this page</a></small>", communication.MediumData["UrlReferrer"]); } BindRecipients(); BindActivity(); ShowActions(communication); }
/// <summary> /// Executes the specified workflow. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="action">The action.</param> /// <param name="entity">The entity.</param> /// <param name="errorMessages">The error messages.</param> /// <returns></returns> public override bool Execute(RockContext rockContext, WorkflowAction action, Object entity, out List <string> errorMessages) { errorMessages = new List <string>(); var mergeFields = GetMergeFields(action); int? fromId = null; Guid?fromGuid = GetAttributeValue(action, "From").AsGuidOrNull(); if (fromGuid.HasValue) { var fromValue = DefinedValueCache.Read(fromGuid.Value, rockContext); if (fromValue != null) { fromId = fromValue.Id; } } var recipients = new List <RecipientData>(); string toValue = GetAttributeValue(action, "To"); Guid guid = toValue.AsGuid(); if (!guid.IsEmpty()) { var attribute = AttributeCache.Read(guid, rockContext); if (attribute != null) { string toAttributeValue = action.GetWorklowAttributeValue(guid); if (!string.IsNullOrWhiteSpace(toAttributeValue)) { switch (attribute.FieldType.Class) { case "Rock.Field.Types.TextFieldType": { recipients.Add(new RecipientData(toAttributeValue)); break; } case "Rock.Field.Types.PersonFieldType": { Guid personAliasGuid = toAttributeValue.AsGuid(); if (!personAliasGuid.IsEmpty()) { var phoneNumber = new PersonAliasService(rockContext).Queryable() .Where(a => a.Guid.Equals(personAliasGuid)) .SelectMany(a => a.Person.PhoneNumbers) .Where(p => p.IsMessagingEnabled) .FirstOrDefault(); if (phoneNumber == null) { action.AddLogEntry("Invalid Recipient: Person or valid SMS phone number not found", true); } else { string smsNumber = phoneNumber.Number; if (!string.IsNullOrWhiteSpace(phoneNumber.CountryCode)) { smsNumber = "+" + phoneNumber.CountryCode + phoneNumber.Number; } var recipient = new RecipientData(smsNumber); recipients.Add(recipient); var person = new PersonAliasService(rockContext).GetPerson(personAliasGuid); if (person != null) { recipient.MergeFields.Add("Person", person); } } } break; } case "Rock.Field.Types.GroupFieldType": case "Rock.Field.Types.SecurityRoleFieldType": { int? groupId = toAttributeValue.AsIntegerOrNull(); Guid?groupGuid = toAttributeValue.AsGuidOrNull(); IQueryable <GroupMember> qry = null; // Handle situations where the attribute value is the ID if (groupId.HasValue) { qry = new GroupMemberService(rockContext).GetByGroupId(groupId.Value); } // Handle situations where the attribute value stored is the Guid else if (groupGuid.HasValue) { qry = new GroupMemberService(rockContext).GetByGroupGuid(groupGuid.Value); } else { action.AddLogEntry("Invalid Recipient: No valid group id or Guid", true); } if (qry != null) { foreach (var person in qry .Where(m => m.GroupMemberStatus == GroupMemberStatus.Active) .Select(m => m.Person)) { var phoneNumber = person.PhoneNumbers .Where(p => p.IsMessagingEnabled) .FirstOrDefault(); if (phoneNumber != null) { string smsNumber = phoneNumber.Number; if (!string.IsNullOrWhiteSpace(phoneNumber.CountryCode)) { smsNumber = "+" + phoneNumber.CountryCode + phoneNumber.Number; } var recipient = new RecipientData(smsNumber); recipients.Add(recipient); recipient.MergeFields.Add("Person", person); } } } break; } } } } } else { if (!string.IsNullOrWhiteSpace(toValue)) { recipients.Add(new RecipientData(toValue.ResolveMergeFields(mergeFields))); } } string message = GetAttributeValue(action, "Message"); Guid messageGuid = message.AsGuid(); if (!messageGuid.IsEmpty()) { var attribute = AttributeCache.Read(messageGuid, rockContext); if (attribute != null) { string messageAttributeValue = action.GetWorklowAttributeValue(messageGuid); if (!string.IsNullOrWhiteSpace(messageAttributeValue)) { if (attribute.FieldType.Class == "Rock.Field.Types.TextFieldType") { message = messageAttributeValue; } } } } if (recipients.Any() && !string.IsNullOrWhiteSpace(message)) { var mediumEntity = EntityTypeCache.Read(Rock.SystemGuid.EntityType.COMMUNICATION_MEDIUM_SMS.AsGuid(), rockContext); if (mediumEntity != null) { var medium = MediumContainer.GetComponent(mediumEntity.Name); if (medium != null && medium.IsActive) { var transport = medium.Transport; if (transport != null && transport.IsActive) { var appRoot = GlobalAttributesCache.Read(rockContext).GetValue("InternalApplicationRoot"); foreach (var recipient in recipients) { var recipientMergeFields = new Dictionary <string, object>(mergeFields); foreach (var mergeField in recipient.MergeFields) { recipientMergeFields.Add(mergeField.Key, mergeField.Value); } var mediumData = new Dictionary <string, string>(); mediumData.Add("FromValue", fromId.Value.ToString()); mediumData.Add("Message", message.ResolveMergeFields(recipientMergeFields)); var number = new List <string> { recipient.To }; transport.Send(mediumData, number, appRoot, string.Empty); } } } } } return(true); }
/// <summary> /// Executes the specified context. /// </summary> /// <param name="context">The context.</param> public virtual void Execute(IJobExecutionContext context) { var rockContext = new RockContext(); var dataMap = context.JobDetail.JobDataMap; resGroupAttribute = AttributeCache.Get(dataMap.GetString(AttributeKey.GroupAttributeSetting).AsGuid()); reservationLocationEntityTypeId = new EntityTypeService(rockContext).GetNoTracking(com.bemaservices.RoomManagement.SystemGuid.EntityType.RESERVATION_LOCATION.AsGuid()).Id; context.Result = "0 meeting reminders sent."; if (resGroupAttribute == null) { var errorMessages = new List <string> { $"The Reservation Group Attribute job setting is invalid. Please check your Room Registration and KFS Zoom Room plugin configuration." }; HandleErrorMessages(context, errorMessages); } var systemCommunicationGuid = dataMap.GetString(AttributeKey.SystemCommunication).AsGuid(); var systemCommunication = new SystemCommunicationService(rockContext).Get(systemCommunicationGuid); var jobPreferredCommunicationType = ( CommunicationType )dataMap.GetString(AttributeKey.SendUsing).AsInteger(); var isSmsEnabled = MediumContainer.HasActiveSmsTransport() && !string.IsNullOrWhiteSpace(systemCommunication.SMSMessage); var isPushEnabled = MediumContainer.HasActivePushTransport() && !string.IsNullOrWhiteSpace(systemCommunication.PushData); if (jobPreferredCommunicationType == CommunicationType.SMS && !isSmsEnabled) { // If sms selected but not usable default to email. var errorMessages = new List <string> { $"The job is setup to send via SMS but either SMS isn't enabled or no SMS message was found in system communication {systemCommunication.Title}." }; HandleErrorMessages(context, errorMessages); } if (jobPreferredCommunicationType == CommunicationType.PushNotification && !isPushEnabled) { // If push notification selected but not usable default to email. var errorMessages = new List <string> { $"The job is setup to send via Push Notification but either Push Notifications are not enabled or no Push message was found in system communication {systemCommunication.Title}." }; HandleErrorMessages(context, errorMessages); } var results = new StringBuilder(); if (jobPreferredCommunicationType == CommunicationType.SMS && string.IsNullOrWhiteSpace(systemCommunication.SMSMessage)) { var warning = $"No SMS message found in system communication {systemCommunication.Title}. All Zoom meeting reminders will be attempted via email."; results.AppendLine(warning); RockLogger.Log.Warning(RockLogDomains.Jobs, warning); jobPreferredCommunicationType = CommunicationType.Email; } if (jobPreferredCommunicationType == CommunicationType.PushNotification && string.IsNullOrWhiteSpace(systemCommunication.PushMessage)) { var warning = $"No Push message found in system communication {systemCommunication.Title}. All Zoom meeting reminders will be attempted via email."; results.AppendLine(warning); RockLogger.Log.Warning(RockLogDomains.Jobs, warning); jobPreferredCommunicationType = CommunicationType.Email; } // Get upcoming Zoom Room occurrences var roomOccurrenceInfo = GetOccurenceAndGroupData(dataMap, rockContext); // Process reminders var meetingRemindersResults = SendMeetingReminders(context, rockContext, roomOccurrenceInfo, systemCommunication, jobPreferredCommunicationType, isSmsEnabled, isPushEnabled); results.AppendLine($"{notificationEmails + notificationSms + notificationPush } meeting reminders sent."); results.AppendLine(string.Format("- {0} email(s)\n- {1} SMS message(s)\n- {2} push notification(s)", notificationEmails, notificationSms, notificationPush)); results.Append(FormatWarningMessages(meetingRemindersResults.Warnings)); context.Result = results.ToString(); HandleErrorMessages(context, meetingRemindersResults.Errors); }
private void SendEmail(string recipient, string subject, RockContext rockContext) { // Resolve the text field merge fields var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields(this.RockPage, _targetPerson); if (_targetPerson != null) { mergeFields.Add("Person", _targetPerson); } string bodyText = GetAttributeValue("EmailBody").ResolveMergeFields(mergeFields); //Get CP Signature var campus = _targetPerson.GetCampus(); var sig = ""; campus.LoadAttributes(); var signatureImage = campus.AttributeValues["CampusPastorSignature"].Value; if (!string.IsNullOrWhiteSpace(signatureImage)) { sig = String.Format( "<img src='https://newpointe.org/GetImage.ashx?guid={0}&width=300' class='img-responsive' />", signatureImage); } // Email Body string body = String.Format(@"{0} <p><span style='font-size:125%; text-transform: uppercase; font-weight: bold;'>{1}<br>{2}</span><br> {3} Pastor ", bodyText, sig, campus.LeaderPersonAlias.Person.FullName, campus.Name); var fromEmailAddress = _targetPerson.GetCampus().LeaderPersonAlias.Person.Email; var fromEmailName = _targetPerson.GetCampus().LeaderPersonAlias.Person.FullName; var fromEmail = String.Format("{0}<{1}>", fromEmailName, fromEmailAddress); // Get the Header and Footer string emailHeader = Rock.Web.Cache.GlobalAttributesCache.Value("EmailHeader"); string emailFooter = Rock.Web.Cache.GlobalAttributesCache.Value("EmailFooter"); var recipients = new List <string>(); recipients.Add(recipient); var mediumData = new Dictionary <string, string>(); mediumData.Add("From", fromEmail); mediumData.Add("Subject", subject); mediumData.Add("Body", emailHeader + body + emailFooter); var mediumEntity = EntityTypeCache.Read(Rock.SystemGuid.EntityType.COMMUNICATION_MEDIUM_EMAIL.AsGuid(), rockContext); if (mediumEntity != null) { var medium = MediumContainer.GetComponent(mediumEntity.Name); if (medium != null && medium.IsActive) { var transport = medium.Transport; if (transport != null && transport.IsActive) { var appRoot = GlobalAttributesCache.Read(rockContext).GetValue("InternalApplicationRoot"); transport.Send(mediumData, recipients, appRoot, string.Empty); } } } }
/// <summary> /// Updates a communication model with the user-entered values /// </summary> /// <param name="communicationService">The service.</param> /// <returns></returns> private Rock.Model.Communication UpdateCommunication(RockContext rockContext, Guid templateGuid) { var communicationService = new CommunicationService(rockContext); var communicationAttachmentService = new CommunicationAttachmentService(rockContext); var communicationRecipientService = new CommunicationRecipientService(rockContext); var MediumEntityTypeId = EntityTypeCache.Read("Rock.Communication.Medium.Email").Id; Rock.Model.Communication communication = null; IQueryable <CommunicationRecipient> qryRecipients = null; CommunicationDetails CommunicationData = new CommunicationDetails(); var template = new CommunicationTemplateService(new RockContext()).Get(templateGuid); if (template != null) { CommunicationDetails.Copy(template, CommunicationData); CommunicationData.EmailAttachmentBinaryFileIds = template.EmailAttachmentBinaryFileIds; } if (communication == null) { communication = new Rock.Model.Communication(); communication.Status = CommunicationStatus.Transient; communication.SenderPersonAliasId = CurrentPersonAliasId; communicationService.Add(communication); } if (qryRecipients == null) { qryRecipients = communication.GetRecipientsQry(rockContext); } communication.IsBulkCommunication = false; var medium = MediumContainer.GetComponentByEntityTypeId(MediumEntityTypeId); if (medium != null) { communication.CommunicationType = medium.CommunicationType; } communication.CommunicationTemplateId = template.Id; //GetMediumData(); foreach (var recipient in communication.Recipients) { recipient.MediumEntityTypeId = MediumEntityTypeId; } CommunicationDetails.Copy(CommunicationData, communication); // delete any attachments that are no longer included foreach (var attachment in communication.Attachments.Where(a => !CommunicationData.EmailAttachmentBinaryFileIds.Contains(a.BinaryFileId)).ToList()) { communication.Attachments.Remove(attachment); communicationAttachmentService.Delete(attachment); } // add any new attachments that were added foreach (var attachmentBinaryFileId in CommunicationData.EmailAttachmentBinaryFileIds.Where(a => !communication.Attachments.Any(x => x.BinaryFileId == a))) { communication.AddAttachment(new CommunicationAttachment { BinaryFileId = attachmentBinaryFileId }, CommunicationType.Email); } communication.FutureSendDateTime = null; return(communication); }