Getting unique emails EWS Managed Web API

1k views Asked by At

I am trying to retrieve the emails from the Exchange server using below code:

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);

        service.Credentials = new WebCredentials("username", "somepassword");

        service.TraceEnabled = true;
        service.TraceFlags = TraceFlags.All;

        service.AutodiscoverUrl("username", RedirectionUrlValidationCallback);


        FindItemsResults<Item> findResults = service.FindItems(WellKnownFolderName.Inbox, new ItemView(10));
        ServiceResponseCollection<GetItemResponse> items =
            service.BindToItems(findResults.Select(item => item.Id), new PropertySet(BasePropertySet.FirstClassProperties, EmailMessageSchema.From, EmailMessageSchema.ToRecipients));
        return items.Select(item =>
        {
            return new MailItem()
            {
                From = ((Microsoft.Exchange.WebServices.Data.EmailAddress)item.Item[EmailMessageSchema.From]).Address,
                Recipients = ((Microsoft.Exchange.WebServices.Data.EmailAddressCollection)item.Item[EmailMessageSchema.ToRecipients]).Select(recipient => recipient.Address).ToArray(),
                Subject = item.Item.Subject,
                Body = item.Item.Body.ToString(),
            };
        }).ToArray();

I need to save the subject and body in my database . But i need unique emails becasue i don't want redundant emails to display on my system.

Means every time i synchronize my system with the exchange server , i will get new emails which i hadn't synchronized yet.

2

There are 2 answers

2
Ephedra On

If I understand you right, you save the emails obtained by EWS in a Database. Later you obtain the emails again and so you get the email you already have plus the new ones?

How about working with timestamps? Get also the CreationTime (or ReceivedTime) of the MailItem and save it in the database too.

After that search in EWS only for mailitems that have CreationTime (or ReceivedTime) later than the last CreationTime (or ReceivedTime) in your Database. So you only get the new emails.

1
Andre Lombaard On

A possible solution is to move the emails that you processed to the DeletedItems folder by calling

emailMessage.Delete(DeleteMode.MoveToDeletedItems);

Please note that I didn't have to keep a copy of the processed emails within my inbox, so this was a viable solution for me. If you for some reason have to keep a copy within your inbox folder this will not work for you.