browse by category or date

Read Email And Send Alerts

Contents

 

My work emails is stored in MS Exchange Server. So I assumed that it would be dead simple to retrieve email using C#. I was wrong. After googling for this solution, I found that many people take the IMAP route instead of using Exchange Web Service API (only available in Exchange 2007 or later). Since I had a very limited time allocated to this project, I follow the recommended IMAP client library, AE.Net.Mail.

We can install this library through Nuget:

Install-Package AE.Net.Mail

This step is quite simple. First, we retrieve the email. Second, check whether the email’s subject is inside the list of subjects that should be relayed to Telegram. If yes, send the message to Telegram. Finally, delete the email regardless it relayed to Telegram or not.

Here’s my code to retrieve the email.

using System;
using System.Configuration;
using AE.Net.Mail;

//..SNIP..

static void Main(string[] args)
{
   var setting = ConfigurationManager.AppSettings;
   var lastRun = DateTime.Now.AddMinutes(-6);
   var imap = new ImapClient(
        setting["emailHost"], 
		setting["emailUser"],
        setting["emailPassword"], 
		AuthMethods.Login, 
		993,  // IMAP secure port
		true, // is Secure?
		true  // skip SSL validation?
   );
   
   // Entity object containing the list of important email subjects
   var db = new ITBotEntities();  
   
   while (true)
   {
      // Check email every 5 minutes
      if (lastRun.AddMinutes(5) < DateTime.Now)
      {
	     
		 var msgs = imap.SearchMessages(
			SearchCondition.Undeleted().And(        
				SearchCondition.SentSince(lastRun)
			));
		 foreach (var msg in msgs)	
		 {
		    //StripSpaces will remove all the whitespaces
		    var subject = StripSpaces(msg.Subject);
		   
		    foreach (var obj in db.LookupParams)
		    {
		       var objHeader = StripSpaces(obj.header);
		 	   if (subject.Equals(objHeader))
			   {					
			      Console.WriteLine(obj.header);
				  //Send alerts to Telegram
				  var content = SendTelegramMessage(obj.header); 
				  Console.WriteLine(content);
			   }
		    }
		    imap.DeleteMessage(msg);
		 }
		 lastRun = DateTime.Now;
	  }
	  else
   	     Thread.Sleep(5000);
   }
}

So how do we actually make the bot send alerts to the group? It's dead simple. Just remember to replace ##TOKEN## and ##GROUP_ID## with values we obtain in step 2.

private static string SendTelegramMessage(string message)
{
	var request =
		WebRequest.Create(
			"https://api.telegram.org/bot##TOKEN##/sendMessage?chat_id=-##GROUP_ID##&text=" +
			WebUtility.UrlEncode(message));
	var resp = request.GetResponse();
	var reader = new StreamReader(resp.GetResponseStream());
	var content = reader.ReadToEnd();
	/*
	the JSON object returned
	{
		"ok": true,
		"result": {
			"message_id": 7,
			"from": {
				"id": 189119520,
				"first_name": "IT-Bot",
				"username": "rlit_bot"
			},
			"chat": {
				"id": -##GROUP_ID##,
				"title": "Richland IT",
				"type": "group"
			},
			"date": 1459696911,
			"text": "Alarm from the Applications Manager - [ EDI File Monitor is down ]"
		}
	}
	
	*/
	reader.Close();
	resp.Dispose();
	return content;
} 
GD Star Rating
loading...
How To Make A Telegram Bot That Sends Alerts When Our Server/Application Is Down, 5.0 out of 5 based on 2 ratings

About Hardono

Howdy! I'm Hardono. I am working as a Software Developer. I am working mostly in Windows, dealing with .NET, conversing in C#. But I know a bit of Linux, mainly because I need to keep this blog operational. I've been working in Logistics/Transport industry for more than 11 years.

Incoming Search

automation, c#, monitoring, telegram

1 comment so far

Add Your Comment
  1. Thanks for sharing the way to make a telegram bot that sends alerts when our server application is down.
    http://rollingskygame.com/