使用Exchange Web Service 2010查找所有未读电子邮件,然后标记为已读?

时间:2013-06-11 18:29:57

标签: c# soap exchangewebservices exchange-server-2010

我正在使用Exchang Web Services 2010尝试从邮箱中读取所有未读的电子邮件,然后将其标记为已读。

我基于这个例子:

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

并想出了这个来查找所有未读电子邮件,并阅读正文内容:

        //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);
        }

这确实会返回所有未读电子邮件正文的文本版本,但是必须有一种更有效的方法,不是吗?

是否有人知道如何将电子邮件MessageType更新为已阅读并将其发送回服务器?

3 个答案:

答案 0 :(得分:5)

我带来了另一个答案元素,以帮助那些和我一样陷入困境的人,以及那些使用EWS 2.0的人:

我在循环中使用Item类型来获取邮箱中的邮件。 Item对象没有IsRead属性(但与EmailMessage对象类似)。所以你可以在循环中用EmailMessage类型替换Item类型(因为允许从Item转换为EmailMessage类型):

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

   }
}

这就是我如何让它发挥作用。

答案 1 :(得分:4)

没有一种方法可以使用EWS v1将MessageType标记为已读。如果您遇到EWS v1,请参阅this MSDN blog post了解解决方法。

EWS v2将IsRead property引入为可写(message.IsRead = true; message.Update();),这使得它变得微不足道。您可以使用适用于Exchange 2007及更高版本的EWS v2托管API,但它是一个单独的安装。有关详情,请参阅MSDN page on EWS Managed API 2.0

答案 2 :(得分:1)

        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