0

I want to take mails from inbox and sentbox folders, compare their subjects and if they match, put it all into a new custom folder. Here's the code so far:

Outlook.MAPIFolder inBox = (Outlook.MAPIFolder)
        this.Application.ActiveExplorer().Session.GetDefaultFolder
        (Outlook.OlDefaultFolders.olFolderInbox);

// I also have made this for the sentBox folder

            string userName = (string)this.Application.ActiveExplorer()
                .Session.CurrentUser.Name;
            Outlook.MAPIFolder customFolder = null;

                customFolder = (Outlook.MAPIFolder)inBox.Folders.Add(userName,
                    Outlook.OlDefaultFolders.olFolderInbox);

                inBox.Folders[userName].Display();

// This is the custom folder in which i wish to place the matching mails

        for (int i = 1; i <= sentboxFolder.Items.Count; i++)
        {
            outboxItem =  sentboxFolder.Items[i];


            for (int a = 1; a <= inBox.Items.Count; a++)
            {
               inboxItem = inBox.Items[a];

                if ("RE: " + outboxItem.Subject == inboxItem.Subject)
                {

                    customFolder.Items.Add(inboxItem);

// Here I loop through the inbox and outbox folders and if the subjects match I want to add the inbox part to the custom folder.

I have 3 questions: 1. Is there a way to put both matching mails into one folder ? 2. I know there should be a smarter way to this aside from comparing subjects, Can anyone help how to use conversation ID here? 3. I get an exception at the last line, that it cannot add inbox item into custom folder because it's not an actual object instance. Where should I instantiate mailitem to fix this ?

Thanks in advance.

1 Answer 1

2

Firstly, do not use multiple dot notation, especially in a loop - cache the Items collection before entering the loop.

Secondly, do not just loop through all items in a folder looking for a match - use Items.Find.

That being said, you can use MailItem.Move(OtherFolder) . If you want to preserve the original item, use MailItem.Copy (returns new item), then move it to the target folder.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.