2015-01-23 2 views
0

Я пытаюсь создать процесс, который будет работать в фоновом режиме непрерывно. Эта служба будет следить за входящими новыми сообщениями электронной почты в папке «Входящие» и «Разбирать электронную почту». У нас есть Exchange Server, поэтому я использую API с управлением Exchange. Я создал класс C#, как указано в документации EWS. У меня есть экземпляр службы, который я тестировал отдельно. Я создаю потоковые уведомления и новое почтовое событие в папке «Входящие». Но я не знаю, как тестировать приложение, так как я запустил окно консоли приложения. Я отправил почту в свой почтовый ящик вручную, но не знаю, когда будет запускаться событие New mail, и если оно отобразит сообщение на консоли. Я не уверен, что нам нужно иметь что-то присутствующее или настроенное на стороне сервера. Я хотел бы знать, есть ли способ сохранить этот процесс без 30 минут. так как я хочу создать сервис. Пожалуйста, ищите помощи.EWS управляемый API, как проверить приложение C#

  namespace NewMailNotification 
      { 
      class Program 
       { 
        static void Main(string[] args) 
         { 
         ExchangeService service = new ExchangeService (ExchangeVersion.Exchange2010_SP2); 

      service.Url = null; 
      string user = ConfigurationSettings.AppSettings["user"]; 
      string userid = ConfigurationSettings.AppSettings["user-id"]; 
      string PWD = ConfigurationSettings.AppSettings["PWD"]; 

      try 
      { 
       service.Credentials = new WebCredentials(user.ToString(), PWD.ToString()); 
       service.AutodiscoverUrl(userid.ToString(), RedirectionUrlValidationCallback); 
      } 
      catch (Exception e) 
      { 
       Console.WriteLine("---" + e.Message); 
      } 

      SetStreamingNotification(service); 

    } 
    private static bool RedirectionUrlValidationCallback(string RedirectionUrl) 
    { 
     bool result = false; 

     Uri redirectionUri = new Uri(RedirectionUrl); 

     if (redirectionUri.Scheme == "https") 
     { 
      Console.WriteLine(redirectionUri); 
      result = true; 
     } 
     return result; 

    } 
    //Notification subscription and event 
    static void SetStreamingNotification(ExchangeService service) 
    { 
     //subscribe to streaming notification onthe inbox folder, and listen to newmail 
     StreamingSubscription streamingsubscription = service.SubscribeToStreamingNotifications(new FolderId[] { WellKnownFolderName.Inbox }, 
      EventType.NewMail, 
      EventType.Created, 
      EventType.Deleted); 

     StreamingSubscriptionConnection connection = new StreamingSubscriptionConnection(service, 30); 

     connection.AddSubscription(streamingsubscription); 

     //Delegate an event handlers 
     connection.OnNotificationEvent += 
      new StreamingSubscriptionConnection.NotificationEventDelegate(OnEvent); 
     connection.OnSubscriptionError += 
      new StreamingSubscriptionConnection.SubscriptionErrorDelegate(OnError); 
     connection.OnDisconnect += 
      new StreamingSubscriptionConnection.SubscriptionErrorDelegate(OnDisconnect); 
     connection.Open(); 

     Console.WriteLine("--------- StreamSubscription event -------"); 
    } 



    static void OnEvent(object sender, NotificationEventArgs args) 
    { 
     StreamingSubscription subscription = args.Subscription; 
     //Loop through all item-related events. 
     foreach(NotificationEvent notification in args.Events) 
     { 
      switch (notification.EventType) 
      { 
       case EventType.NewMail: 
        Console.WriteLine("\n----------------Mail Received-----"); 
        break; 
       case EventType.Created: 
        Console.WriteLine("\n-------------Item or Folder deleted-------"); 
        break; 
       case EventType.Deleted: 
        Console.WriteLine("\n------------Item or folder deleted---------"); 
        break; 
      } 
      //Display the notification identifier. 
      if (notification is ItemEvent) 
      { 
       //The notificationEvent for a folder is a Folderevent. 
       FolderEvent folderevent = (FolderEvent)notification; 
       Console.WriteLine("\nFolderId: " + folderevent.FolderId.UniqueId); 
      } 
      else 
      { 
       //The notificationevent for a foler is a FolderEvent 
       FolderEvent folderevent = (FolderEvent)notification; 
       Console.WriteLine("\nFolderId: " + folderevent.FolderId.UniqueId); 

      } 
     } 
    } 


    static private void OnDisconnect(object sender, SubscriptionErrorEventArgs args) 
    { 
     StreamingSubscriptionConnection connection = (StreamingSubscriptionConnection)sender; 
     //ask the usr if they want to reconnect or close the connection 
     ConsoleKeyInfo cki; 
     Console.WriteLine("The connection to the subscription is disconnected."); 
     Console.WriteLine("Do you want to reconnect to the subscription? Y/N"); 
     while (true) 
     { 
      cki = Console.ReadKey(true); 
      { 
       if (cki.Key == ConsoleKey.Y) 
       { 
        connection.Open(); 
        Console.WriteLine("Connection Open."); 
        Console.WriteLine("\r\n"); 
        break; 
       } 
       else if (cki.Key == ConsoleKey.N) 
       { 
        // Signal.Set(); 
        bool isOpen = connection.IsOpen; 

        if (isOpen == true) 
        { 
         connection.Close(); 
        } 
        else 
        { 
         break; 
        } 

       } 
      }//while end 
     } 
    } 

     static void OnError(object sender,SubscriptionErrorEventArgs args) 
     { 
      Exception e=args.Exception; 
      Console.WriteLine("\n------------Error----"+e.Message+"----------"); 
     } 
    }//class end 

} // конец пространства имен

ответ

0

Вот код, чтобы заставить ее работать. Я могу смотреть входящую электронную почту на 30 монетных дворов. Хотя предыдущий код будет работать с учетной записью с одним почтовым ящиком. Но если у вас более двух почтовых ящиков, мы должны указать почтовый ящик, который нам нужно посмотреть.

 static void Main(string[] args) 
    { 
     ExchangeService service = new ExchangeService (ExchangeVersion.Exchange2010_SP2); 
     //***********New********************** 
     ExchangeService mailbox = new ExchangeService(ExchangeVersion.Exchange2010_SP2); 
     string mailboxEmail = ConfigurationSettings.AppSettings["user-id"]; 
     WebCredentials wbcred = new WebCredentials(ConfigurationSettings.AppSettings["user"], ConfigurationSettings.AppSettings["PWD"]); 
     mailbox.Credentials = wbcred; 
    // mailbox.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, mailboxEmail); 

      mailbox.AutodiscoverUrl(mailboxEmail, RedirectionUrlValidationCallback); 
     mailbox.HttpHeaders.Add("X-AnchorMailBox", mailboxEmail); 
     FolderId mb1Inbox = new FolderId(WellKnownFolderName.Inbox, mailboxEmail); 
     SetStreamingNotification(mailbox, mb1Inbox); 
     bool run = true; 
     while (run) 
     { 
      System.Threading.Thread.Sleep(100); 
     } 
    } 

    internal static bool RedirectionUrlValidationCallback(string redirectionUrl) 
    { 
     //The default for the validation callback is to reject the URL 
     bool result=false; 

     Uri redirectionUri=new Uri(redirectionUrl); 
     if(redirectionUri.Scheme=="https") 
     { 
      result=true; 
     } 
     return result; 
    } 

    static void SetStreamingNotification(ExchangeService service,FolderId fldId) 
    { 
     StreamingSubscription streamingssubscription=service.SubscribeToStreamingNotifications(new FolderId[]{fldId}, 
      EventType.NewMail, 
      EventType.Created, 
      EventType.Deleted); 

     StreamingSubscriptionConnection connection=new StreamingSubscriptionConnection(service,30); 
     connection.AddSubscription(streamingssubscription); 

     //Delagate event handlers 
     connection.OnNotificationEvent+=new StreamingSubscriptionConnection.NotificationEventDelegate(OnEvent); 
     connection.OnSubscriptionError+=new StreamingSubscriptionConnection.SubscriptionErrorDelegate(OnError); 
     connection.Open(); 

    } 

    static void OnEvent(object sender,NotificationEventArgs args) 
    { 
     StreamingSubscription subscription=args.Subscription; 
     if(subscription.Service.HttpHeaders.ContainsKey("X-AnchorMailBox")) 
     { 
      Console.WriteLine("event for nailbox"+subscription.Service.HttpHeaders["X-AnchorMailBox"]); 
     } 
     //loop through all the item-related events. 
     foreach(NotificationEvent notification in args.Events) 
     { 
      switch(notification.EventType) 
      { 
       case EventType.NewMail: 
        Console.WriteLine("\n----------------Mail Received-----"); 
        break; 
       case EventType.Created: 
        Console.WriteLine("\n-------------Item or Folder deleted-------"); 
        break; 
       case EventType.Deleted: 
        Console.WriteLine("\n------------Item or folder deleted---------"); 
        break; 

      } 

      //Display notification identifier 
      if(notification is ItemEvent) 
      { 
       //The NotificationEvent for an email message is an ItemEvent 
       ItemEvent itemEvent=(ItemEvent)notification; 
       Console.WriteLine("\nItemId:"+ itemEvent.ItemId.UniqueId); 
       Item NewItem=Item.Bind(subscription.Service,itemEvent.ItemId); 
       if(NewItem is EmailMessage) 
       { 
        Console.WriteLine(NewItem.Subject); 
       } 

      } 
      else 
      { 
       //the Notification for a Folder is an FolderEvent 
       FolderEvent folderEvent=(FolderEvent)notification; 
       Console.WriteLine("\nFolderId:"+folderEvent.FolderId.UniqueId); 
      } 
     } 
    } 
    static void OnError(object sender,SubscriptionErrorEventArgs args) 
    { 
     //Handle error conditions. 
     Exception e=args.Exception; 
     Console.WriteLine("\n-----Error-----"+e.Message+"--------"); 
    } 
} 

}

0

Здравствуйте, я сделал то же самое я должен создать консольное приложение, и я не закрывать консольное приложение.

Последняя строка У меня есть запись является «Console.ReadLine()»

когда вы получили новое сообщение электронной почты, то OnNotificationEvent событие будет срабатывать.

Ниже приведен пример кода.

class Program 
    { 
     static void Main(string[] args) 
     { 
      EmailExchange emailExchange = new EmailExchange(); 
      emailExchange.Domain = ConfigurationManager.AppSettings["Domain"]; 
      emailExchange.EmailID = ConfigurationManager.AppSettings["EmailID"]; 
      emailExchange.Password = ConfigurationManager.AppSettings["Password"];     
      emailExchange.Watch(); 

      Console.ReadLine(); 
     } 

    } 


public class EmailExchange : IDisposable 
    { 
     public string Password { get; set; } 
     public string EmailID { get; set; } 
     public string Domain { get; set; }    
     public string ExchangeURL 
     { 
      get { return "https://outlook.office365.com/EWS/Exchange.asmx"; } 
     }   
     private StreamingSubscriptionConnection connection = null; 
     private ExchangeService service = null; 
     public void Watch() 
     { 
      service = new ExchangeService(); 
      service.Credentials = new WebCredentials(EmailID, Password, Domain);    
      service.Url = new Uri(ExchangeURL); 
      StreamingSubscription streamingsubscription = service.SubscribeToStreamingNotifications(new FolderId[] { WellKnownFolderName.Inbox }, EventType.NewMail);    
      connection = new StreamingSubscriptionConnection(service, 5); 
      connection.AddSubscription(streamingsubscription); 
      connection.OnNotificationEvent += OnNotificationEvent; 
      connection.OnSubscriptionError += OnSubscriptionError; 
      connection.OnDisconnect += OnDisconnect; 
      connection.Open(); 
     } 

     private void OnDisconnect(object sender, SubscriptionErrorEventArgs args) 
     { 
      Console.WriteLine("Disconnected"); 
      if (!connection.IsOpen) 
       connection.Open(); 
     } 

     private void OnSubscriptionError(object sender, SubscriptionErrorEventArgs args) 
     { 

     } 

     private void OnNotificationEvent(object sender, NotificationEventArgs args) 
     { 
      foreach (var notification in args.Events) 
      { 
       if (notification.EventType != EventType.NewMail) continue; 

       var itemEvent = (ItemEvent)notification;    
       // add you code here 
      } 
     } 



     public void Dispose() 
     { 
      GC.SuppressFinalize(this); 
     } 
    } 
Смежные вопросы