1

I have to write a code when the user clicks on the Send button to move a mailitem to a folder My Folder and stop the sending functionality. I have achieved this through Below Code:

       void Application_ItemSend(object Item, ref bool Cancel)
        {
                Outlook.MailItem mailItem = Item as Outlook.MailItem;
                Cancel = true;
                if (mailItem != null)
                {
                    var attachments = mailItem.Attachments;

                    string folderPath =
                      Application.Session.
                      DefaultStore.GetRootFolder().FolderPath
                      + @"\Outbox\My Outbox";
                    Outlook.Folder folder = GetFolder(folderPath);
                    if (folder != null)
                    {
                        mailItem.Move(folder);

                    }
                  }
         }

My question is that I have to trigger a code piece when a mailitem arrive in the My Outbox folder. I am a newbie in VSTO and plugins . Kindly tell me how can I achieve this. Any help will be highly appreciated.

Nitin Rawat
  • 209
  • 1
  • 5
  • 14

1 Answers1

1

If you want to detect when an item has been added into a Outlook folder you need to use the ItemAdd event on the Items collection of the Folder.

Below is an example on how to detect when a MailItem is added into the Inbox folder. Add the following code in the ThisAddIn.cs file:

private Items _inboxItems;

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    MAPIFolder inboxFolder = Application.GetNamespace("MAPI").GetDefaultFolder(OlDefaultFolders.olFolderInbox);
    _inboxItems = inboxFolder.Items;

    _inboxItems.ItemAdd += InboxItems_ItemAdd;

    Marshal.ReleaseComObject(inboxFolder);
}

private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
    Marshal.ReleaseComObject(_inboxItems);
}

private void InboxItems_ItemAdd(object item)
{    
    if (item is MailItem)
    {
        // Add your code here        
    }
}
m_collard
  • 2,008
  • 4
  • 29
  • 51
  • FYI, the ItemAdd event is not 100% reliable if more than 16 items are being delivered/copied/moved to the folder at the same time - so there's a chance a message could be missed. For handling newly delivered emails specifically, you can use the Application.NewMail or Application.NewMailEx events. – Eric Legault Jul 04 '14 at 17:07