I am working on an Outlook AddIn with a custom ribbon. The user opens a mail item in Read mode and clicks a button on the ribbon and the program will move the email to a folder (not the user's personal mailbox, but rather to a different mailbox that user has access to).
When the program is run, it works the first time, but the second time the user runs it, it throws an error:
"The attempted operation failed. An object could not be found."
Here is the relevant code:
(in ThisAddIn.cs)
public partial class ThisAddIn
{
public Outlook.Application OutlookApplication;
void ThisAddIn_Startup(object sender, System.EventArgs e)
{
OutlookApplication = this.Application;
}
(etc)
(In Ribbon1.cs, in a method that gets called upon button_Click)
Outlook.Inspector inspector = Globals.ThisAddIn.OutlookApplication.ActiveInspector();
Outlook.MailItem item = inspector.CurrentItem as Outlook.MailItem;
Outlook.Stores stores = null;
Outlook.Folder destinationMailboxFolderInbox = null;
and
try
{
// Set the mailbox move location
stores = Globals.ThisAddIn.OutlookApplication.GetNamespace("MAPI").Stores;
foreach (Outlook.Store store in stores)
{
attachmentsFoundTotal++;
if (store.DisplayName == destinationMailbox)
{
destinationMailboxFolderInbox = (Outlook.Folder)store.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
try
{
// the code breaks on this line below:
item.Move(destinationMailboxFolderInbox.Folders[destinationMailboxFolder]);
}
catch (Exception ex3)
{
System.Windows.Forms.MessageBox.Show(ex3.Message + " Could not find Outlook folder " + destinationMailboxFolder + ". The mail item was not moved." );
}
}
}
}
catch (Exception ex2)
{
System.Windows.Forms.MessageBox.Show(ex2.Message);
}
UPDATE: After trial & error testing, the only way I could resolve the Outlook 2010 bug was to have the Outlook view switch to the folder where the mail item was moved, using this command after the command to move the item to myfolder.
Globals.ThisAddIn.OutlookApplication.ActiveExplorer().CurrentFolder = myFolder;