Find all unread emails using Exchange Web Service 2010 then mark as read?
Asked Answered
I

3

9

I'm using Exchang Web Services 2010 to try and read all unread emails from a mailbox, then mark them as read.

I'm basing off this example:

http://msdn.microsoft.com/en-us/library/exchange/aa563373(v=exchg.140).aspx

And have come up with this to find all unread emails, and read the body contents:

        //Set up the connection to exchange service
        ExchangeServiceBinding exchangeService = new ExchangeServiceBinding();
        exchangeService.Credentials = new NetworkCredential("userid", "password", "domain");
        exchangeService.Url = "https://exchangeserver/ews/exchange.asmx";

        //REturn all properties
        FindItemType findType = new FindItemType();
        findType.Traversal = ItemQueryTraversalType.Shallow;
        findType.ItemShape = new ItemResponseShapeType();
        findType.ItemShape.BaseShape = DefaultShapeNamesType.AllProperties;

        //Only search the inbox
        DistinguishedFolderIdType[] foldersToSearch = new DistinguishedFolderIdType[1];
        foldersToSearch[0] = new DistinguishedFolderIdType();
        foldersToSearch[0].Id = DistinguishedFolderIdNameType.inbox;
        findType.ParentFolderIds = foldersToSearch;

        //Only unread emails
        RestrictionType restriction = new RestrictionType();
        IsEqualToType isEqualTo = new IsEqualToType();
        PathToUnindexedFieldType pathToFieldType = new PathToUnindexedFieldType();
        pathToFieldType.FieldURI = UnindexedFieldURIType.messageIsRead;

        //Not IsRead
        FieldURIOrConstantType constantType = new FieldURIOrConstantType();
        ConstantValueType constantValueType = new ConstantValueType();
        constantValueType.Value = "0";
        constantType.Item = constantValueType;
        isEqualTo.Item = pathToFieldType;
        isEqualTo.FieldURIOrConstant = constantType;
        restriction.Item = isEqualTo;

        //set the not IsRead restriction
        findType.Restriction = restriction;

        try
        {
            FindItemResponseType findResponse = exchangeService.FindItem(findType);
            ResponseMessageType[] responseMessType = findResponse.ResponseMessages.Items;

            List<ItemIdType> unreadItemIds = new List<ItemIdType>();

            //get all unread item IDs
            foreach (ResponseMessageType respMessage in responseMessType)
            {
                if(respMessage is FindItemResponseMessageType)
                {
                    FindItemResponseMessageType itemResponse = (FindItemResponseMessageType)respMessage;

                    if (itemResponse.ResponseClass == ResponseClassType.Success)
                    {
                        if (itemResponse.RootFolder.Item != null)
                        {

                            if (itemResponse.RootFolder.Item is ArrayOfRealItemsType)
                            {
                                ArrayOfRealItemsType items = (ArrayOfRealItemsType)itemResponse.RootFolder.Item;

                                if (items.Items != null)
                                {
                                    ItemType[] itemTypes = items.Items;

                                    foreach (ItemType item in itemTypes)
                                    {
                                        if (item is MessageType)
                                        {
                                            unreadItemIds.Add(item.ItemId);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if (unreadItemIds.Count == 0)
                MessageBox.Show("No unread emails found");
            else
            {
                //Get all unread mail messages, display body
                GetItemType getItemType = new GetItemType();
                getItemType.ItemShape = new ItemResponseShapeType();
                getItemType.ItemShape.BaseShape = DefaultShapeNamesType.AllProperties;
                getItemType.ItemShape.BodyType = BodyTypeResponseType.Text;
                getItemType.ItemShape.BodyTypeSpecified = true;
                getItemType.ItemIds = unreadItemIds.ToArray();

                GetItemResponseType getItemResponse = exchangeService.GetItem(getItemType);

                if(getItemResponse.ResponseMessages != null)
                {
                    ArrayOfResponseMessagesType responseMessages = getItemResponse.ResponseMessages;
                    foreach(ResponseMessageType responseMessage in responseMessages.Items)
                    {
                        if (responseMessage is ItemInfoResponseMessageType)
                        {
                            ItemInfoResponseMessageType responseItemInfo = (ItemInfoResponseMessageType)responseMessage;
                            if (responseItemInfo.Items != null)
                            {
                                ArrayOfRealItemsType responseRealItems = (ArrayOfRealItemsType)responseItemInfo.Items;

                                if (responseRealItems.Items != null)
                                {
                                    foreach (ItemType responseItemType in responseRealItems.Items)
                                    {
                                        if (responseItemType is MessageType)
                                        {
                                            MessageType fullMessage = (MessageType)responseItemType;

                                            BodyType body = fullMessage.Body;

                                            if (body != null)
                                            {
                                                MessageBox.Show(body.Value);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        catch(Exception ee)
        {
            MessageBox.Show(ee.Message +" " + (ee.InnerException ?? new Exception("")).Message);
        }

That does return the text version of all unread email bodies, however there must be a more effecient way, no?

Does anyone know how I can update the email MessageTypes as read and have it send back to the server?

Illa answered 11/6, 2013 at 18:29 Comment(0)
A
6

There is not a good way to mark a MessageType as read using EWS v1. See this MSDN blog post for a workaround if you are stuck with EWS v1.

EWS v2 introduced the IsRead property as writable (message.IsRead = true; message.Update();), which makes it trivial. You can use the EWS v2 managed API for Exchange 2007 and above, but it is a separate installation. See the MSDN page on EWS Managed API 2.0 for more.

Archil answered 12/6, 2013 at 6:22 Comment(3)
Thanks Mitch, but are you sure you linked to the right blog post?Illa
I'm using EWS 2.0 with an Exchange 2013 and I don't have any IsRead property from message object. I have the following beginning by "Is" :IsAssociated, IsAttachment, IsDirty, IsDraft, IsFromMe, IsNew, IsReminderSet, IsResend, IsSubmitted and IsUnmodified. Do I have to activate something or to use a property of property ? If someone can please help me, thx.Kalpak
It sounds like you are dealing with an type of Item (msdn.microsoft.com/en-us/library/…). IsRead exists on EmailMessage (msdn.microsoft.com/en-us/library/…). Make sure you are hitting the right class.Archil
K
5

I'm bringing another answer element in order to help those who fell in the same trap as me , and for those using EWS 2.0 :

I was using an Item type in my loop to fetch the mails in the mailbox. And the Item object don't have the IsRead property (but is similar to the EmailMessage object). So you can just replace the Item type by EmailMessage type in your loop (because the cast is allowed from Item to EmailMessage type) :

foreach (EmailMessage message in findResults.Items)
{
   if(message.IsRead==false) //if the current message is unread
   {
      //treatment
   } 
   else
   {

   }
}

That's how I got it to work.

Kalpak answered 19/3, 2014 at 13:49 Comment(0)
L
3
        For Each appointment As EmailMessage In service.FindItems(WellKnownFolderName.Inbox, New SearchFilter.SearchFilterCollection(LogicalOperator.And, New SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, False)), New ItemView(999))
            ' set as read 
            appointment.IsRead = True
            appointment.Update(ConflictResolutionMode.AlwaysOverwrite)
        Next
Leptosome answered 20/3, 2014 at 19:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.