2

I am new to Outlook Addin development. I was writing a simple application that printed out the name of the folder that an email was dragged into. IE: Inbox to Subfolder in Inbox. The issue I have is that sometimes the correct MailItem.Parent.Name is returned but the majority of the time its the source folder and not the destination. I dont understand why this might be because the event should be firing for the ItemAdd on the destination.

Here is some code:

public Microsoft.Office.Interop.Outlook.Application OutlookApplication;
public Inspectors OutlookInspectors;
public Inspector OutlookInspector;
public MailItem OutlookMailItem;
private MAPIFolder inboxFolder;
private MailItem msg;
private Folder fdr;

public void OnConnection(object application, Extensibility.ext_ConnectMode connectMode, object addInInst, ref System.Array custom)
{
  OutlookApplication = application as Microsoft.Office.Interop.Outlook.Application;
  OutlookInspectors = OutlookApplication.Inspectors;
  OutlookInspectors.NewInspector += new Microsoft.Office.Interop.Outlook.InspectorsEvents_NewInspectorEventHandler(OutlookInspectors_NewInspector);

  inboxFolder = this.OutlookApplication.Session.GetDefaultFolder(OlDefaultFolders.olFolderInbox);

  foreach (Folder f in inboxFolder.Folders)
  {
    f.Items.ItemAdd += new ItemsEvents_ItemAddEventHandler(InboxItems_ItemAdd);
  }
}

void InboxItems_ItemAdd(object Item)
{
  msg = Item as MailItem;
  fdr = msg.Parent as Folder;

  MessageBox.Show("Folder Name: " + fdr.Name);
}
Y0rk1e
  • 117
  • 1
  • 4

1 Answers1

0

I don't know how you even get the Items.ItemAdd event to fire. I could not get your example working so I created my own. The following worked for me every time and it always shows the target folder name. If you don't specifically keep a collection of Outlook.Items as a class member, the events will never get triggered. See related SO post.

private Outlook.Folder inbox;
private List<Outlook.Items> folderItems = new List<Outlook.Items>();

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    inbox = this.Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox) as Outlook.Folder;
    for (int i = 1; i < inbox.Folders.Count+1; i++)
    {
        folderItems.Add((inbox.Folders[i] as Outlook.Folder).Items);
        folderItems[i - 1].ItemAdd += (item) =>
        {
            Outlook.MailItem msg = item as Outlook.MailItem;
            Outlook.Folder target = msg.Parent as Outlook.Folder;
            string folderName = target.Name;
        };
    }
}
Community
  • 1
  • 1
SliverNinja - MSFT
  • 31,051
  • 11
  • 110
  • 173