Below is my working code snippet that retrieves unread emails from custom folder names under Inbox.
foreach (Microsoft.Exchange.WebServices.Data.Folder folder in findFolderResults.Folders)
{
LogFile.AppendLog(folder.DisplayName + " folder found in Inbox.");
if (folder.DisplayName == folderName)
{
LogFile.AppendLog(folder.DisplayName + " matches " + folderName);
ItemView view = new ItemView(emailBatch);
do
{
LogFile.AppendLog("Checking for unread emails in folder " + folder.DisplayName);
emailItemList = service.FindItems(folder.Id, sf, view);
foreach (var emailItem in emailItemList.Items)
{
LogFile.AppendLog("Getting unread emails in folder " + folder.DisplayName);
EmailMessage email = EmailMessage.Bind(service, emailItem.Id);
retrievedEmailList.Add((EmailMessage)email);
}
if (!emailItemList.NextPageOffset.HasValue)
break;
}
while (emailItemList.MoreAvailable);
}
}
There is a variable emailBatch
that is currently being configured as 10
.
I do understand that this means that it will only check and retrieve 10
unread email at one go.
However, once the 10
email has been added to the list, will it continue to check for unread email?
I would need to add all unread emails to retrievedEmailList
, instead of just 10 emails, if it happens.
Thank you.
You need to implement paged searching. You seem to have partially tried this but your code is missing some stuff. I have updated your code and put comments in explaining the new code I've added.
// Set the offset for the paged search.
int offset = 0;
// Set the flag that indicates whether to continue iterating through additional pages.
bool MoreItems = true;
LogFile.AppendLog(folder.DisplayName + " folder found in Inbox.");
if (folder.DisplayName == folderName)
{
// Continue paging while there are more items to page.
while (MoreItems)
{
LogFile.AppendLog(folder.DisplayName + " matches " + folderName);
// Set the ItemView with the page size and offset.
ItemView view = new ItemView(emailBatch, offset, OffsetBasePoint.Beginning);
LogFile.AppendLog("Checking for unread emails in folder " + folder.DisplayName);
emailItemList = service.FindItems(folder.Id, sf, view);
foreach (var emailItem in emailItemList.Items)
{
LogFile.AppendLog("Getting unread emails in folder " + folder.DisplayName);
EmailMessage email = EmailMessage.Bind(service, emailItem.Id);
retrievedEmailList.Add((EmailMessage)email);
}
// Set the flag to discontinue paging.
if (!emailItemList.MoreAvailable)
MoreItems = false;
// Update the offset if there are more items to page.
if (MoreItems)
offset += pageSize;
}
}