I need to sort my emails by Received time before processing them as I am processing emails and entering data from it into a database.
I need it so the newest email to be received gets put into the database to overwrite the older version (If there is an older version).
Microsoft.Office.Interop.Outlook.Items item = (Outlook.Items)source.Items;
Source is the folder with the emails in it that I wanted sorted
I have tried these four ways:
items.Sort("ReceivedTime", false);
items.Sort("[ReceivedTime]", Outlook.OlSortOrder.olAscending);
items.Sort("ReceivedTime", Outlook.OlSortOrder.olSortNone);
items.Sort("[ReceivedTime]");
Which does not seem to sort it as It still puts the oldest into the database second, overwriting the newest submission.
Any Ideas?
it should be
items.Sort("[ReceivedTime]", false);
or true
if you want them descending
I spent so much time trying to figure out the same problem.
It appears there is some sort of bug in Microsoft Interop.outlook that if you directly try to sort from folder it does not work at all.
Microsoft.Office.Interop.Outlook.Application app = new Microsoft.Office.Interop.Outlook.Application(); Microsoft.Office.Interop.Outlook._NameSpace ns = app.GetNamespace("MAPI"); Microsoft.Office.Interop.Outlook.MAPIFolder inboxFolder = null; inboxFolder = ns.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
inboxFolder.Items.Sort("[ReceivedTime]", false); foreach (var item in inboxFolder.Items) { // ITEMS ARE NOT SORTED }
To make it work you must copy them in different list and then sort. The example below will work.
Outlook.Application app = new Outlook.Application(); Outlook.NameSpace outlookNs = app.GetNamespace("MAPI"); Outlook.MAPIFolder emailFolder = outlookNs.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox); Outlook.Items myItems = emailFolder.Items; myItems.Sort("[ReceivedTime]", false); foreach (var item in myItems) { var itemObj = item as MailItem; if (itemObj != null) { // This time it will work } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With