Send Mails from Event Hub via Azure Functions

Azure Event Hubs is an event ingestion service for big data streaming workloads. It is capable of receiving and processing millions of events per second. Data sent to an event hub can be transformed and stored by using any real-time analytics provider or batching/storage adapters.

It can also be used to receive Machine’s Telemetry data in a Manufacture Organization. A monitoring and alerting system can be deployed on Event Hubs.

In this article, we will learn to send an email with SendGrid for disconnected Machines based on the telemetry data received in the Event Hub. SendGrid is a cloud-based email service that provides reliable transactional email delivery, scalability, and real-time analytics along with flexible APIs that make custom integration easy

So Let’s begin.

Pre-requisites

  • Event Hub Should be up and running.
  • Events Data received by Event Hub should have below Schema:
{
   "MachineName":"AB01",
   "ServerName":"XXXYYZZZZ01",
   "Process":"CNC",
   "LastStatus":3,
   "Status":"Connect",
   "Time":"2020-05-30T16:18:31.7058659Z"
}

Create SendGrid Account

  • Go to SendGrid Accounts. Click on Add
  • Provide Details and click on create
  • Click on Manage
  • Click on Settings > API Keys
  • Click on Create API Key
  • Provide Key Name, Select Full Access and Click on Create and View.

Create Azure Function App

  • Go to Function App. Click on Add
  • Provide details and click on Review + Create

Create a Function

  • Click on Functions > Add
  • Click on Event Hub Trigger
  • Provide Details and Click on Create Function. Ensure to select Correct event hub
  • Click on Code +Test. Paste below code in Code Window. Ensure to replace place holder and other details in the code. Replace <placeholders> with actual values.
#r "Microsoft.Azure.EventHubs"
#r "SendGrid"
#r "Newtonsoft.Json"
 
 
 
using System;
using System.Text;
using Microsoft.Azure.EventHubs;
using SendGrid;
using SendGrid.Helpers.Mail;
using Newtonsoft.Json;
 
 
public static async Task Run(EventData[] events, ILogger log)
{
  var apiKey = "<API KEY>";
  var client = new SendGridClient(apiKey);
  var msg = new SendGridMessage()
  {
     From = new EmailAddress("xxx@outlook.com", "Operations Team"),
     Subject = "Alert",
     PlainTextContent = "Hello, Mail from Azure Function!",
     HtmlContent = "<strong>Hello, Mail from Azure Function!</strong>"
 
  };

  foreach (EventData eventData in events)
  {
    try
{
        string messageBody = Encoding.UTF8.GetString(eventData.Body.Array, eventData.Body.Offset, eventData.Body.Count);
        
ServerDetails serverDetails = JsonConvert.DeserializeObject<ServerDetails>(messageBody);
        var MachineName = serverDetails.MachineName;
        var ServerName = serverDetails.ServerName;
        var Process = serverDetails.Process;
        var Status = serverDetails.Status;
        var Time = serverDetails.Time;
        if(Status == "Disconnect"){
        DateTime reportedtime = DateTime.Now;
        reportedtime = reportedtime.ToUniversalTime();
        TimeSpan difference = reportedtime - Time;
        int downtimedays = difference.Days;
        if(downtimedays > 1) {
         msg.AddTo(new EmailAddress("xxx@contoso.com", "Test User"));
         msg.Subject = $"Alert : Machine {MachineName} Disconneted for more than 2 days";
         msg.PlainTextContent =$"Server Details: {MachineName}{ServerName}{Process}{Status}{Time}";
         msg.HtmlContent = $"<strong>Alert: Server Details: {MachineName}{ServerName}{Process}{Status}{Time}</strong>";
         var response = await client.SendEmailAsync(msg);
 
        log.LogInformation($"Mail Alert Response {response.StatusCode}");
         await Task.Yield();
         log.LogInformation($"Mail Alert Sent");
         }
       }
     }
   catch (Exception e)

   {
       log.LogInformation($"Error{e}");
 
  }
 }
}
 
public class ServerDetails
{
    public string MachineName { get; set; }
    public string ServerName { get; set; }
    public string Process { get; set; }
    public int  LastStatus { get; set; }
    public string Status { get; set; }
    public DateTime Time { get; set; }
}

In the above code, we created a ServerDetails Class to capture and de-serialize the events data. Once the events data is de-serialized, we checked if the Machine has been disconnected for more than 1 day and then, prepared the message body for the mail with details. We log the Mail Sent activity for auditing purposes.

In this article, we have learnt to Send Mails from Event Hubs with SendGrid service on Azure.

One thought on “Send Mails from Event Hub via Azure Functions

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create your website at WordPress.com
Get started
%d bloggers like this: