Set restriction to get messages older than a specific date using EWS?

Hi, I'm new working with EWS and I have found some code to set a restriction to help me filter messages "between" to dates, but I need to be able to obtain emails that are "older" than a specific date so I can delete them.  My application needs to be
able to clean up a mailbox to only to keep up to so many days/weeks worth of emails.  The code I have to search for emails that works
between dates is:
public void SetDateRestriction(FindItemType findItemRequest)
DateTime dateStart = DateTime.Now;
DateTime dateEnd = DateTime.Today.AddDays(-180);
PathToUnindexedFieldType dateSentPath = new PathToUnindexedFieldType();
dateSentPath.FieldURI = UnindexedFieldURIType.itemDateTimeSent;
IsGreaterThanOrEqualToType isGreaterThanOrEqual = new IsGreaterThanOrEqualToType();
isGreaterThanOrEqual.Item = dateSentPath;
FieldURIOrConstantType dateConstant = new FieldURIOrConstantType();
ConstantValueType dateConstantValue = new ConstantValueType();
//dateConstantValue.Value = string.Format("{0}-{1}-{2}T00:00:00Z", dateStart.Year.ToString(), dateStart.Month.ToString(), dateStart.Day.ToString());
dateConstantValue.Value = dateStart.ToUniversalTime().ToString("yyyy-MM-ddT00:00:00Z");
dateConstant.Item = dateConstantValue;
isGreaterThanOrEqual.FieldURIOrConstant = dateConstant;
// less than or equal to
PathToUnindexedFieldType dateSentPath1 = new PathToUnindexedFieldType();
dateSentPath1.FieldURI = UnindexedFieldURIType.itemDateTimeSent;
IsLessThanOrEqualToType lessThanOrEqualTo = new IsLessThanOrEqualToType();
lessThanOrEqualTo.Item = dateSentPath1;
FieldURIOrConstantType dateConstant1 = new FieldURIOrConstantType();
ConstantValueType dateConstantValue1 = new ConstantValueType();
//dateConstantValue1.Value = string.Format("{0}-{1}-{2}T00:00:00Z", dateEnd.Year.ToString(), dateEnd.Month.ToString(), dateEnd.Day.ToString());
dateConstantValue1.Value = dateEnd.ToUniversalTime().ToString("yyyy-MM-ddT00:00:00Z");
dateConstant1.Item = dateConstantValue1;
lessThanOrEqualTo.FieldURIOrConstant = dateConstant1;
RestrictionType restriction = new RestrictionType();
AndType andType = new AndType();
andType.Items = new SearchExpressionType[] { lessThanOrEqualTo , isGreaterThanOrEqual };
restriction.Item = andType;
findItemRequest.Restriction = restriction;
How can I modify this to give me emails older than a specific date?  Also any input on doing the deleting would also be greatly appreciated!
Best Regards,
Nelson

Thank you very much Glen!  I can't believe it was that easy.  Works perfect.  I will work on the DeleteItemType.  I was also wondering if there was a way to detect if an email is an Out-of-Office (OOO) or Undeliverable message? 
My app goes through all the emails and I need to skip any that are OOO or Undeliverable messages.  I've learned how to use the SearchFilter and I find that easier and more straight forward than setting the restrictions.  I'm also able to use a SearchFilter
to get emails older than the specified date. 
Here's my new code for reading unread emails using the SearchFilter and paging (for better efficiency). 
1 - Is there anyway to tell the filter to get AllProperties without having to specify each one using ItemSchema or EmailMessageSchema?
2- What is the difference between those two (any advantages over one or the other)?
3 -Is there any reason to even be using the ExchangeServiceBinding here anymore since it seems the ExchangeService object is all I need?  In my old code, I was using the ExchangeService object to do an AutoDiscover and then using that to set the URL
in the ExchangeServiceBinding.  What are the main to difference/uses for these to objects?  Sorry if that's a dumb question.
private void GetUnReadEmails(string sMailboxName)
// Create the binding to Exchange
ExchangeServiceBinding esb = new ExchangeServiceBinding();
esb.RequestServerVersionValue = new RequestServerVersion();
//Console.WriteLine("Exchange version: " + esb.RequestServerVersionValue.Version);
//esb.RequestServerVersionValue.Version = ExchangeVersionType.Exchange2007_SP1;
ExchangeService service = GetBinding(sMailboxName);
Console.WriteLine("Exchange version: " + service.RequestedServerVersion);
esb.Url = service.Url.ToString();
esb.Credentials = new NetworkCredential(Username, Password, Domain);
Mailbox mb = new Mailbox(sMailboxName);
FolderId fid1 = new FolderId(WellKnownFolderName.Inbox, mb); // where fid1 was WellKnownFolderName.Inbox
//FindFoldersResults findResults = service.FindFolders(fid1, new FolderView(int.MaxValue));
ItemView iv = new ItemView(50, 0);
FindItemsResults<Item> findResults = null;
PropertySet ivPropSet = new PropertySet(BasePropertySet.IdOnly);
//SearchFilter ivSearchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false), new SearchFilter.ContainsSubString(ItemSchema.Subject,"MSGID:"));
SearchFilter searchFilter = new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false);
iv.PropertySet = ivPropSet;
do
findResults = service.FindItems(fid1, searchFilter, iv);
string sText = "";
if(findResults.Items.Count > 0)
//PropertySet itItemPropSet = new PropertySet(BasePropertySet.IdOnly) { EmailMessageSchema.Body };
PropertySet itemPropSet = new PropertySet(BasePropertySet.IdOnly) {ItemSchema.Subject, ItemSchema.Body, ItemSchema.DateTimeReceived, ItemSchema.HasAttachments, ItemSchema.ItemClass};
itemPropSet.RequestedBodyType = BodyType.Text;
service.LoadPropertiesForItems(findResults.Items, itemPropSet);
//service.LoadPropertiesForItems(findResults.Items, itItemPropSet);
//service.LoadPropertiesForItems(findResults, new PropertySet(ItemSchema.Subject, ItemSchema.Body, ItemSchema.DateTimeReceived));
Console.WriteLine("Total items: " + findResults.TotalCount);
foreach (Item item in findResults.Items)
Console.WriteLine("ItemID: " + item.Id.UniqueId);
Console.WriteLine("Subject: " + item.Subject);
Console.WriteLine("Received date: " + item.DateTimeReceived);
Console.WriteLine("Body: " + item.Body);
Console.WriteLine("Has attachments: " + item.HasAttachments);
//Mark the email as read
EmailMessage emEmail = EmailMessage.Bind(service, item.Id);
//emEmail.Load();
emEmail.IsRead = true;
emEmail.Update(ConflictResolutionMode.AlwaysOverwrite);
sText += "Subject: " + (item.Subject.Trim()) + " ";
//sText += "DisplayTo: " + (item.DisplayTo.Trim()) + " ";
sText += "DateTimeReceived: " + (item.DateTimeReceived.ToString()) + " ";
sText += "ItemClass: " + (item.ItemClass.Trim()) + " ";
sText += "\r\n";
else
sText = "No unread emails";
Console.WriteLine("No unread emails");
txtItems.Text = sText;
iv.Offset += findResults.Items.Count;
} while (findResults.MoreAvailable == true);
Thanks again for your time.  I appreciate it.
Nelson

Similar Messages

  • Searching for calendar items older than a specific date with search-mailbox and AQS

    I need to find the total size of all calendar items in a mailbox older than a specified date using PowerShell through the search-mailbox cmdlet's searchquery parameter.  My problem is that I cannot find a complete list of Calendar item properties to
    use in search queries.  The AQS page doesn't have a complete list of properties for a Calendar object.
    I'm using code from the ArchiveStatisticsPlanner.ps1 script as a base and the only date properties I know of are the sent and receive properties (see below.)  The basic start, end, date properties generate errors in the query.  How can I find all
    Calendar items older than say, 1/1/2013?
    Sample:
    $MBXSearch=Search-Mailbox-Identity$MBX-SearchQuery"kind:calendar
    sent:<=$QueryDate OR kind:calendar received:<=$QueryDate"-EstimateResultOnly-DoNotIncludeArchive

    huh, you a get response marked as answer that wasn't very helpful.
    EDIT: and now I'm reported as abusive.  Please don't tell the truth on these forums, it seems to be frowned upon
    I did that.
    If you're going to necro an answered thread and attempt to hijack it, you should have an actual answer that you feel is more relevant.
    All you did was complain and add zero useful information, thus earning an 'offtopic/irrelevant' notation.
    Don't retire TechNet! -
    (Don't give up yet - 13,085+ strong and growing)

  • Exchange 2010 Outlook search can not find messages older than 1 year

    Hello,
    I have an exchange 2010 sp2 server. One of my users complains that Outlook search can not find any message older than 1 year. He have all his 5 year mails in the mailbox, but looks like search engine cant recognise them :( 
    Any thoughts? thanks in advance.

    Hi,
    Please verify that indexing is complete in Outlook:
    1. In Outlook, click in the Search box.
    2. Click the Search tab, click Search Tools, and then click Indexing Status.
    3. When the Indexing Status dialog appears, you should see the following:
    Outlook has finished indexing all of your items.
    0 items remaining to be indexed.
    Besides, please use the Search-Mailbox cmdlet to check if you can get messages older than one year in this user mailbox.
    Best regards,
    Belinda
    Belinda Ma
    TechNet Community Support

  • How can I set up a rule to delete all messages older than 6 months left in Apple Mail's main inbox?

    How can I set up a rule to delete all messages older than 6 months left in Apple Mail's main inbox?
    I have created other rules to move some of my daily messages into specific folders and I don't wish to auto-delete those.
    Just the general stuff that keeps piling up in my me.com main email box.  Mail such as FB announcements and other low priority stuff I want to look at before deleting but don't want to keep longer than a week or month.
    TIA
    thokitts

    Thanks, but I am looking for a more automated solution than hand marking emails as junk. I might as well move them to the trash myself.
    Again, these are emails I want to receive and quickly read, but not keep longer than a week or month or so. By setting a rule to toss any older than 30 days back then my Mail program (and thus my hard drive) won't be wasting so much space. For example, currently I have over 6000 read messages, with their attachments, in my main email box. I'd rather not have to physically attend to sorting the one I don't want out.
    The one I do keep for other reasons get moved into other folders.
    It seems this should be possible.
    thokitts

  • Message older than allowed MessageAge Error while invoking webservice

    Hi,
    I have a web service using, implementation is annotated with Wssp1.2-2007-Https-UsernameToken-Plain.xml Policy. I am using a java client based no static Service model to connect to the server.
    When I try to connect to the webservice from local machine it works fine.
    If I connect from a remote machine below exception is thrown. Even If I set both machines to same time zones and tame same exception is thrown.
    ( client running on windows, server running on linux)
    How can I fix this ? Is there a way to configure MessageAge ? or disable it ?
    Exception in thread "main" javax.xml.ws.soap.SOAPFaultException: Security token
    failed to validate. weblogic.xml.crypto.wss.SecurityTokenValidateResult@18216e3[
    status: false][msg UNT Error:Message older than allowed MessageAge]
    at com.sun.xml.ws.fault.SOAP11Fault.getProtocolException(SOAP11Fault.jav
    a:196)
    at com.sun.xml.ws.fault.SOAPFaultBuilder.createException(SOAPFaultBuilde
    r.java:122)
    at com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.
    java:119)
    at com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.
    java:89)
    at com.sun.xml.ws.client.sei.SEIStub.invoke(SEIStub.java:118)
    at $Proxy36.getAllRootDisTags(Unknown Source)
    at SampleNIClient.main(SampleNIClient.java:75)

    Hello -
    This is the webservice policy violation from client side.
    Mainly the time difference is the route cause.
    By default WLS will allow up to 300 sec for client message.
    You can change the setting by editing the following...
    Go to Security Realms >myrealm >Providers >DefaultIdentityAsserter
    Then edit Digest Expiration Time Period value according to your requirement.
    Regards,
    Justin.

  • Delete messages older than a date except personal folder

    Hello everyone,
    I have been spending a lot of time searching and testing how to delete all items older than 6 months in a user mailbox, but this rule it cannot be applied just one personal folder named "personal". I have been reading about retention policy and
    retention policy tags, but I can't figure out how to use that to keep all items older than 6 month in personal folder.
    could anyone tell me if I am right with retention policy or it's better other way?
    thank you in advice

    Hi,
    In Outlook client, we can set AutoArchive for all folders to delete all items older than 6 months except for “Personal” folder one by one.
    If you want to use retention policy in Exchange side, we can use retention tags and retention policies to have a try. there are three types of retention tags:
    Default policy tag (DPT), Retention policy tag (RPT), Personal tag.
    For your scenario, we can create a personal tag applied for this Personal folder. For example,
    delete messages older than 3 years for this personal folder. Then apply this personal tag for Personal folder in Outlook. And the Personal folder items are all tagged. After that, we can
    applying default policy tags (DPTs) to mailboxes to manage the retention of all untagged items.
    Personal suggestion, since the delete action is only used for one specific mailbox, I suggest we can use AutoArchive in Outlook side to achieve it.
    Regards,
    Please remember to mark the replies as answers if they help, and unmark the answers if they provide no help. If you have feedback for TechNet Support, contact [email protected]
    Winnie Liang
    TechNet Community Support
    Hi Winnie Liang,
    Thank you for answer. I would like to do all tasks from exchange side, so I know how to apply a retention policy to a mailbox for deleting all older than 6 months. But how can I apply the personal policy tag to a personal folder's users?
    All involved users in this requirement are warned that they must let all personal messages in "personal" folder named "personal".
    regards

  • Is there a way to print texts/messages older than 90 days from phone without wireless printer?

    Is there a way to print texts/messages older than 90 days from phone without wireless printer?

    thanks for the reply....but forwarding to my email  - well, there were too many that I wanted printed.  But do appreciate your answering. 

  • Voice Memos older than last Sync date not copying from iPhone to PC after sync, even though "Include voice memos" is checked

    I am trying to copy over my voice memos from my iPhone to my PC. I have "Include voice memos" checked under the Music tab.
    I had an issue with voice memos being duplicated on my iPhone after a sync (I got two versions of each memo on my phone for some reason), so after deleting the extra copies on my phone I deleted all voice memos from within iTunes and chose the option to move the files to the Recycle Bin. So the Music\iTunes\Itunes Music\Voice Memos folder is empty, and there are no voice memos showing up in iTunes.
    But now when I sync, it isn't copying over the older memos that are on my iPhone to my computer. If I record a new voice memo then that memo transfers successfully, but any voice memos with a recording date older than my last sync date do not transfer.
    How can I get these older voice memos (with dates older than my last sync date) transferred over from my phone onto my PC?

    Does anyone know of a way that I can access the voice memos with dates older than my last sync date...?

  • Primarily using the ipad air as an art portfolio but photos i upload in order get rearranged. other than changing the date they were shot, is there any solution to this? can they be reorganized in iphoto on the ipad?

    primarily using the ipad air as an art portfolio but photos i upload in order get rearranged. other than changing the date they were shot, is there any solution to this? can they be reorganized in iphoto on the ipad?

    You are welcome.
    Sorting and organizing photos on IOS devices is one of the things that really need to be improved. It looks like the developers simply did not expect the users to want to keep large photo libraries on an IOS device, where the ordering would matter. I'd send feedback to the developer team, so that they see, what the users want and need:
    You can use this form:  Apple - iPhoto - Feedback

  • Upgrading to Lightroom 5.6 get message "Windows cannot access specific device path or file. You may not have the appropriate permissions to access the item" I'm running Windows 7. How do I make it work?

    Upgrading to Lightroom 5.6 get message "Windows cannot access specific device path or file. You may not have the appropriate permissions to access the item" I'm running Windows 7. How do I make it work?

    right click the installation file and click 'run as administrator'.

  • Update Date is older than the Creation Date

    Hi Team,
    In the Oracle Application 11i forms we are seeing the Update Date is older than the Creation Date?
    But the creation date should be older then the updated date.
    Thanks,

    What 11i release are you on?
    Can you please elaborate more on the Creation/Update dates mentioned above? Are you referring to forms or tables or specific rows? Is this happening to all data/forms? Please provide an example for us to understand your issue.
    Thanks,
    Hussein

  • Viewing messages older than ten days in iMessage

    Good day. I want to look back in a chat history, but when I get to messages more than ten days old iMessage stops retrieving them. My preferences are set to keep messages forever. I have an iPhone 5c with iOS 8, and I do not use iMessage on my desktop machine.
    Thanks for any insights you may have!

    Did you back your phone up?
    Also sometimes the iMessage contains a combination of text and iMessages - the text messages are not recoverable
    Did you upgrade the iOS in the last few days or reset your phone?
    http://www.macworld.co.uk/how-to/iosapps/fix-ios-imessage-problems-bug-messages- not-delivered-3470405/

  • TS4002 Messages older than 30 days in inbox are not moved to deleted items when removed.

    I've had a few messages that were stored in my inbox and were older than 30 days. I've noticed that when I actually delete them they aren't moved to Deleted Items (and sat for 30 days before permanently deleted). It seems that the actual date of the email is being used to calculate the age and not the time it sits in deleted items.

    If deleted email isn't being moved to the trash you might want to go to icloud.com from your computer, open mail, click on the gear-shaped icon on the top right and choose preferences, then confirm on the General tab that you have checked "Move deleted messages to" and selected "Tash" from the drop-down list.

  • Mail lists messages older than Yesterday with 27 March 09

    My mail is received under the heading Date Received: as Today, Yesterday and 27 March 09. If I open the message with 27 March 09 the correct date and time is displayed in the message header. the time received is correct on all messages.
    All messages in my various folders older than two days are dated 27 March 09. Any ideas.

    With respect to having Mail store your Sent messages you must choose whether they are to be stored on the server (if .mac or IMAP account), and for how long to store them.
    Before making this change, you should have created an On My Mac mailbox (this would be separate from the one for the account) and transferred the older messages to that mailbox.
    However, in this case, since Spotlight finds some messages, you should look with the Finder in Home/Library/Mail/Mailboxes and see if there is an xxxx.mbox folder that was storing the Sent messages previously. If so, rename it, and it should show up in the Sidebar to the Mail window -- this might require reindexing via the Rebuild command.
    More info after making this examination, and before renaming of making any other changes.
    Ernie
    Message was edited by: Ernie Stamper

  • Inbox loses all messages older than one/two days

    So, I'm the proud new owner of an iPhone, and while I'm generally very happy with it, I'm having some email troubles that I hope someone here might help me sort out.
    The issue is that all the messages that come into my mailbox disappear after a day or two, which negates (at least for me) any advantage to having on-the-go email. My iPhone is set up to receive email from a POP account, and so far, I've had no problems receiving or sending mail - it's the not-deleting-emails-from-my-inbox issue that's giving me fits.
    At first, I thought it might have something to do with the settings on the desktop computer (Mac Pro) which is also set up to receive emails from this account. The mail application on the desktop had been set to delete all messages from the server a week after the message had been retrieved. Given that the messages in my iphone are deleted from the iphone's inbox a day (at most two) after retrieving the message, I don't think this is an issue (in any case, i am under the impression that the iphone works like any other email application - once it retrieves a message, it is downloaded onto the device, correct? it doesn't just live on the server). In any event, to be on the safe side, I changed the Mac Pro's email settings to never delete messages from the server, but this hasn't affected my iphone's problem.
    I've toyed around with the iphone's settings, but nowhere can I find a setting that addresses this specific problem. Anyone out there had the same trouble I'm having? If so, were you able to fix it? is it something I'm overlooking?
    Thanks in advance.

    That is the correct spot, what is/was that option set to under deleted Messages? Try setting it to Never and see if that might change the emails behavior. If that is not the cause then it might be a issue with the Mail Application Software on the phone in your particular case and would need to restore the phone.
    Another thing to try is to remove the email account on the phone then re-add the account and see if it is doing the same thing.

Maybe you are looking for