Below is an example of .Net core 3.1 Console App that is reading a mailbox on Exchange and checking the count of mails. If the mail count cross a certain threshold, it’ll check for an e-mail older than 2 hours to send an alert.
Such an example can be used to schedule alerts or log information if you’re tracking mails in a mailbox.
Install Nuget package Microsoft.Exchange.WebServices to use ExchangeService class.
using Microsoft.Exchange.WebServices.Data;
public static void Main(string[] args)
{
string TextlogMessage;
string Subject = "";
string sUsername = ConfigurationManager.AppSettings.Get("UserName");
var section = ConfigurationManager.GetSection("secureAppSettings") as NameValueCollection;
string vCount = ConfigurationManager.AppSettings.Get("Count");
int Count = Convert.ToInt32(vCount);
string sPassword = ConfigurationManager.AppSettings.Get("Password");
string sDomain = ConfigurationManager.AppSettings.Get("Domain");
TimeZoneInfo INDIAN_ZONE = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
DateTime indianTime = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, INDIAN_ZONE);
DateTime comparedate = indianTime.AddHours(-2);
DateTime MailDateTime = comparedate;
ExchangeService exchange = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
exchange.Credentials = new WebCredentials(sUsername, sPassword, sDomain);
exchange.Url = new Uri(ConfigurationManager.AppSettings.Get("ExchangeUrl"));
Folder inbox = Folder.Bind(exchange, WellKnownFolderName.Inbox);
var oSendemail = 0;
TextlogMessage = "Start With count:" + inbox.TotalCount;
if (inbox.TotalCount > Count)
{
Console.WriteLine("Count " + inbox.TotalCount);
ItemView view = new ItemView(1);
view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending);
var findResults = exchange.FindItems(WellKnownFolderName.Inbox, view);
foreach (Item item in findResults.Items)
{
Console.WriteLine("Test: " + item.DateTimeReceived + " %" + comparedate);
DateTime newdate = TimeZoneInfo.ConvertTimeToUtc(item.DateTimeReceived);
int Dresult = DateTime.Compare(newdate, comparedate);
if (Dresult < 0)
{
Console.WriteLine("Alert " + "Sub" + item.Subject + newdate + " %" + comparedate);
oSendemail = 1;
MailDateTime = newdate;
Subject = item.Subject;
}
}
if (oSendemail > 0)
{
Program p = new Program();
//To Do Send Email Logic..
p.SendEmail(exchange, oSendemail, inbox.TotalCount, TextlogMessage);
TextlogMessage = TextlogMessage + " EmailTime: " + MailDateTime + "CompareTime " + comparedate + " Alert Sent Subject : " + Subject;
}
}
//To Do logging..
log(TextlogMessage);
}