I am new to EWS and I am trying to run my email parser console app real-time where it receives new emails. Someone suggested Push notifications but then I stumbled upon Streaming Notifications which I find easier. I based my codes here: Set streaming notifications for applications programmatically but I encountered a problem because I don't know where should I insert my codes for email parsing.
Here are my codes: (Email Parsing is inside the OnEvent here)
private static void Main(string[] args)
{
ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2); // coect to exchange server
//service.UseDefaultCredentials = true; // only tu this on if the user's credential is logged in to windows
service.Credentials = new WebCredentials("email address", "password");
service.TraceEnabled = true;
//service.TraceFlags = TraceFlags.All;
service.AutodiscoverUrl("email address", RedirectionUrlValidationCallback);
SetStreamingNotifications(service);
// Wait for the application to exit
Signal = new AutoResetEvent(false);
Signal.WaitOne();
}
static void SetStreamingNotifications(ExchangeService service)
{
// Subscribe to streaming notifications on the Inbox folder, and listen
// for "NewMail", "Created", and "Deleted" events.
StreamingSubscription streamingsubscription = service.SubscribeToStreamingNotifications(
new FolderId[] { WellKnownFolderName.Inbox },
EventType.NewMail);
StreamingSubscriptionCoection coection = new StreamingSubscriptionCoection(service, 20);
coection.AddSubscription(streamingsubscription);
// Delegate event handlers.
coection.OnNotificationEvent +=
new StreamingSubscriptionCoection.NotificationEventDelegate(OnEvent);
coection.OnSubscriptionError +=
new StreamingSubscriptionCoection.SubscriptionErrorDelegate(OnError);
coection.OnDiscoect +=
new StreamingSubscriptionCoection.SubscriptionErrorDelegate(OnDiscoect);
coection.Open();
}
private static void OnEvent(object sender, NotificationEventArgs args)
{
StreamingSubscription subscription = args.Subscription;
//loop through all the item-related events.
foreach (NotificationEvent notification in args.Events)
{
if (notification.EventType != EventType.NewMail) continue;
Console.WriteLine("A new mail has been created");
var itemEvent = (ItemEvent)notification;
Console.WriteLine("The item ID of the new mail is {0}", itemEvent.ItemId.UniqueId);
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2); // coect to exchange server
SearchFilter sf = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false)); // searching unread emails
FindItemsResults<Item> items = service.FindItems(WellKnownFolderName.Inbox, sf, new ItemView(int.MaxValue)); // retrieve
PropertySet ItemPropertySet = new PropertySet(BasePropertySet.IdOnly);
ItemPropertySet.Add(ItemSchema.Body);
ItemPropertySet.RequestedBodyType = BodyType.Text; // convert the html email body into plain text
if (items.Items.Count > 0)
{
Console.WriteLine("New email from inbox..."); // loading emails
service.LoadPropertiesForItems(items.Items, ItemPropertySet);
}
foreach (Item item in items.Items)
{
EmailMessage email = EmailMessage.Bind(service, item.Id);
Console.WriteLine("From: " + email.From);
Console.WriteLine("Subject: " + email.Subject);
Console.WriteLine("Received At: " + email.DateTimeReceived.ToString("dd MMMM yyyy"));
Console.WriteLine("Body: " + item.Body.Text);
email.IsRead = true; // mark as read
string from = (email.From).Name.ToString();
string eadd = (email.From).Address.ToString();
string subject = email.Subject;
string body = item.Body.Text;
Regex r = new Regex("Building:\s(\d)\s*Level:\s(\d)\s*Phase:\s(\d+)\s*Request:\s(.*)", RegexOptions.IgnoreCase | RegexOptions.Singleline); // extracting values from the email body
Match m = r.Match(body);
String d1 = m.Groups[1].ToString();
String d2 = m.Groups[2].ToString();
String int1 = m.Groups[3].ToString();
String word1 = m.Groups[4].ToString();
if (m.Success)
{
EmailParser parse = new EmailParser() // coect to database
{
From = from,
Email_Address = eadd,
Subject = subject,
Building = d1,
Level = d2,
Phase = int1,
Request = word1
};
OfficeDataContext dbContext = new OfficeDataContext();
dbContext.EmailParsers.InsertOnSubmit(parse);
dbContext.SubmitChanges();
}
}
}
}
static private void OnDiscoect(object sender, SubscriptionErrorEventArgs args)
{
// Cast the sender as a StreamingSubscriptionCoection object.
StreamingSubscriptionCoection coection = (StreamingSubscriptionCoection)sender;
coection.Open();
}
static void OnError(object sender, SubscriptionErrorEventArgs args)
{
// Handle error conditions.
Exception e = args.Exception;
Console.WriteLine("n-------------Error ---" + e.Message + "-------------");
}
Am I doing this wrong?
