Tom
Tom

Reputation: 51

C# Outlook isn't moving all emails

I'm using the Outllok Interop to move emails from one folder to another (after getting all of the attachments, but that works) but it isn't copying all of the emails. I've tried putting a wait in, but it doesn't have an effect. First it'll move 6, then 3, then 1. Can anyone tell me why its not moving them all?

Relevant code is below:

Application oOutlook = new Application();
NameSpace oNs = oOutlook.GetNamespace("MAPI");

Recipient oRep = oNs.CreateRecipient("ContentHelp");
MAPIFolder inbox = oNs.GetSharedDefaultFolder(oRep, OlDefaultFolders.olFolderInbox);

MAPIFolder nihSub = inbox.Folders["NIH"];
MAPIFolder nihArchive = inbox.Folders["NIHarchive"];
Items nihItems = nihSub.Items;
MailItem moveMail = null;
//inboxItems = inboxItems.Restrict("[Unread] = false");

int increment = 0;

try
{
    foreach (object collectionItem in nihItems)
    {
        moveMail = collectionItem as MailItem;
        if (moveMail != null)
        {
            Console.WriteLine("Moving {0}", moveMail.Subject.ToString());
            string titleSubject = (string)moveMail.Subject;
            moveMail.Move(nihArchive);
        }
    }
}

Upvotes: 5

Views: 2746

Answers (4)

Harisha
Harisha

Reputation: 11

for (int j= items.Count();j>=1; j--){
  dynamic item = newItems[j] ;
  if (item is MailItem){
     item.Move();
  }
}

Upvotes: 0

Zoltan Vegh
Zoltan Vegh

Reputation: 11

Not so pretty, but it works:

Outlook.Folder FolderInbox = NameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox) as Outlook.Folder;
List<Outlook.MailItem> MailItemList = new List<Outlook.MailItem>();
foreach (Outlook.MailItem item in FolderInbox.Items.OfType<Outlook.MailItem>())
    MailItemList.Add(item);
foreach (Outlook.MailItem item in MailItemList)
    ProcessMail(item);

Upvotes: 1

76mel
76mel

Reputation: 4043

The index gets reset each time you loop on move , so you will never more than half the items. Use a While loop or countdown from olItems.Count to 1.

Upvotes: 6

Nathan Koop
Nathan Koop

Reputation: 25197

A backwards loop is one that goes from the max to the min.

IE:

for(int i = 10; i>0; i--)
{
     Console.WriteLine(i);
}

For this instance you could use something like: (please note I haven't tested with the outlook objects so some tweaking may be required)

        for (int i=nihItems.count; i >= 0; i--)
        {
            moveMail collectionItem = nihItems[i] as MailItem

            if (moveMail != null)
            {
                Console.WriteLine("Moving {0}", moveMail.Subject.ToString());
                string titleSubject = (string)moveMail.Subject;
                moveMail.Move(nihArchive);
            }
         }

Upvotes: 2

Related Questions