private async Task TriggerEmailAction(ExecutionContext context, ActionEvent actionInfo, RuleAction action) { var hasRecipients = action.Parameters.TryGetValue("Recipients", out object recipientsResult); if (!hasRecipients) { throw new ArgumentException("The given email action has no listed recipients"); } var recipients = new List <string>(); try { var recipientsJArray = (JArray)recipientsResult; recipients = recipientsJArray.Select(token => token.Value <string>()).ToList(); } catch (InvalidCastException ice) { throw new ArgumentException("The given email action did not have a 'Recipients' parameter that could be converted to a list of strings", ice); } if (recipients.Count == 0) { throw new ArgumentException("The given email action did not contain any recipients"); } action.Parameters.TryGetValue("Subject", out object subject); action.Parameters.TryGetValue("Notes", out object notes); var timeReceived = new DateTime(1970, 1, 1).AddMilliseconds(double.Parse(actionInfo.DeviceMsgReceived)); var messageInfo = new EmailFormatModel { Recipients = recipients, Subject = (string)subject, DeviceId = actionInfo.DeviceId, Description = actionInfo.RuleDescription, Severity = actionInfo.RuleSeverity, Time = timeReceived.ToString(), Notes = (string)notes, }; var message = EmailMessageHelper.GenerateAlertEmailMessage(context, messageInfo); await this.EmailClient.SendEmailAsync(message); }
public static SendGridMessage GenerateAlertEmailMessage(ExecutionContext context, EmailFormatModel messageInfo) { var msg = new SendGridMessage(); msg.SetFrom(new EmailAddress(EmailFrom, EmailFromMessage)); msg.AddTos(messageInfo.Recipients.Select(email => new EmailAddress(email)).ToList()); if (!string.IsNullOrEmpty(messageInfo.Subject)) { msg.SetSubject($"{EmailSubjectPrefix}: {messageInfo.Subject}"); } else { msg.SetSubject(EmailSubjectPrefix); } Func <IDictionary <string, object>, string> template; string templateFilePath = Path.Combine(context.FunctionAppDirectory, "Files", "AlertEmail.html"); using (Stream stream = File.OpenRead(templateFilePath)) using (StreamReader reader = new StreamReader(stream)) { template = Mustachio.Parser.Parse(reader.ReadToEnd()); } // Set the model with the necessary template format values dynamic model = new ExpandoObject(); model.DeviceId = messageInfo.DeviceId; model.Description = messageInfo.Description; model.Severity = messageInfo.Severity; model.Time = messageInfo.Time; model.Notes = messageInfo.Notes; msg.AddContent(MimeType.Html, template(model)); return(msg); }