'outlook interop application doesn't get all emails C#
I'm trying to get outlook Email using Microsoft.Office.Interop.Outlook but in cases where the folder has a lot of emails (for example 1904 Emails) I'm getting only 571 emails.
here's my code:
Application oApp = new Application();
_NameSpace oNS = (_NameSpace)oApp.GetNamespace("MAPI");
MAPIFolder inbox = oNS.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
var emails = inbox.Items;
int emailsCount = emails.Count;
when I open outlook I see the number 1904 next to the Inbox folder, but when I scroll down I see the line "there are more items in this folder on the sever"
dose anyone know how can I download all my Emails using outlook interop?
Solution 1:[1]
this is my code from a working app:
A lot of it seems cracking a nut with a sledge hammer however, this hasnt failed me in many years.
MAPIFolder f;
int retries = 0;
while (!connected && retries < 2)
{
doUpdateStatus("Connecting");
try
{
app = new Application();
NameSpace ns = app.GetNamespace("MAPI");
f = ns.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
doUpdateStatus("Connected to outlook");
doUpdateStatus("Walking Outlook Folders .. Please wait");
try
{
doUpdateStatus("");
if (DoSync)
{
try
{
doUpdateStatus("Syncing");
SyncObject _syncObj = null;
_syncObj = ns.SyncObjects.AppFolders;
_syncObj.SyncEnd += _syncObj_SyncEnd;
ns.SendAndReceive(false);
syncing = true;
_syncObj.Start();
while (syncing)
{
Thread.Sleep(10);
}
connected = true;
}
catch
{
doUpdateStatus("Sync failed");
}
finally
{
syncing = false;
}
}
else
{
doUpdateStatus("Outlook sync disabled");
connected = true;
}
}
catch
{
doUpdateStatus("Unable to connect to Outlook and Load folders");
app.Quit();
retries++;
Thread.Sleep(5000);
}
}
catch
{
doUpdateStatus("Unable to connect to Outlook");
if (app!=null) app.Quit();
retries++;
Thread.Sleep(5000);
}
}
private static void _syncObj_SyncEnd()
{
syncing = false;
}
Solution 2:[2]
You can either force Outlook to download all items (make sure the slider in the Exchange account properties is set to "All' rather than something like "12 months") or you can reopen the folder in the online mode - in Extended MAPI (C++ or Delphi), you can do that by using the MAPI_NO_CACHE flag when calling IMAPISession::OpenEntry or IMsgStore::OpenEntry. If Extended MAPI is not an option, you can use Redemption (I am its author):
MAPI_NO_CACHE = &H200
MAPI_BEST_ACCESS = &H10
set OutlookFolder = Application.ActiveExplorer.CurrentFolder
set Session = CreateObject("Redemption.RDOSession")
Session.MAPIOBJECT = Application.Session.MAPIOBJECT
set OnlineFolder = Session.GetFolderFromID(OutlookFolder.EntryID, OutlookFolder.StoreID, MAPI_NO_CACHE + MAPI_BEST_ACCESS)
MsgBox OnlineFolder.Items.Count
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | BugFinder |
Solution 2 |