0
votes

I am trying to get a specific email from from EWS using C# but could not find a way to identify a specific email.

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
            service.Credentials = new WebCredentials(myemail, password);
            service.UseDefaultCredentials = false;
            service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
            ItemView itemsView = new ItemView(5);
            string querystring = "Kind:email";                

            FindItemsResults<Item> itemResults = service.FindItems(WellKnownFolderName.Inbox, querystring, view: itemsView);

The FindItems method gives emails based on query string. I save EmailMessage.InternetMessageId and EmailMessage.Id and subject etc details in my database. In my case I may have emails with same subject and little different body content.

Later, based on user action I want to get specific email from exchange server. Is there any method I can use and get email based on EmailMessage.InternetMessageId or EmailMessage.Id ? Are these Ids reliable? I could not find a method in docs. Currently I am thinking of read emails based on subject and then filter the results based on EmailMessage.Id.UniqueId

Is there any good alternate way to get specific email from exchange server?

1

1 Answers

1
votes

The IntenetMessageId should be unique but there is no guarantee that it will be because of the number of different processes that can set the Id's.

If you want to get a specific message based on its InternetMessageId then you need to use the Extended property rather then the strongly typed one eg

  String MessageID = "<blah@1223434556com">"
  ItemView ivew = new ItemView(3);
  service.TraceEnabled = true;
  ExtendedPropertyDefinition PidTagInternetMessageId = new ExtendedPropertyDefinition(4149, MapiPropertyType.String);
  SearchFilter sf = new SearchFilter.IsEqualTo(PidTagInternetMessageId, MessageID);
  FindItemsResults<Item> iCol = service.FindItems(WellKnownFolderName.Inbox, sf, ivew);

  foreach (Item item in iCol.Items)
  {
    Console.WriteLine(item.Subject);
  }

You can export the message to a EML file using https://docs.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-export-items-by-using-ews-in-exchange