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.



Categories: Azure, Azure Functions

Tags: , , ,

11 replies

  1. Reblogged this on xAFTERHOURSx and commented:
    Great post!

  2. hey there and thank you for your info – I’ve definitely
    picked up anything new from right here. I did however expertise several technical points
    using this site, since I experienced to reload the web site lots of times previous to
    I could get it to load properly. I had been wondering if your web hosting is OK?
    Not that I’m complaining, but sluggish loading instances times will very frequently
    affect your placement in google and can damage your quality score if advertising and
    marketing with Adwords. Anyway I am adding this RSS to my e-mail and
    could look out for a lot more of your respective fascinating content.

    Make sure you update this again soon.

  3. Good way of explaining, and pleasant paragraph to take information on the topic of my presentation focus, which i am going to convey
    in institution of higher education.

  4. Way cool! Some extremely valid points! I appreciate you writing this write-up
    and the rest of the website is extremely good.

  5. An outstanding share! I have just forwarded this onto a colleague who was conducting a
    little homework on this. And he actually bought me breakfast simply because I discovered
    it for him… lol. So let me reword this…. Thanks for the meal!!
    But yeah, thanx for spending time to discuss this subject here on your web site.

  6. These are actually great ideas in on the topic of blogging.
    You have touched some fastidious things here.
    Any way keep up wrinting.

Leave a Reply

Discover more from Cloud Wizard Inc.

Subscribe now to keep reading and get access to the full archive.

Continue reading