Identify the selected attachment in the MailItem object

Add-in Express™ Support Service
That's what is more important than anything else

Identify the selected attachment in the MailItem object
 
Zach Jeyakaran




Posts: 120
Joined: 2011-09-07
Hello,

I have an existing object model that uses MailItem objects to do work on MailItem Attachments. What I want to do now is to remove unselected attachments from the MailItem so I can process them using existing code. Here is an example of what I want to do (questions are in comments at the end of the code):

private void attachmentContextButton_OnClick(object sender, AddinExpress.MSO.IRibbonControl control, bool pressed)
{
        var context = control.Context;
        if (context == null) return;
        insp = OutlookApp.ActiveInspector();
        exp = OutlookApp.ActiveExplorer();
        if (insp != null)
        {
          item = (MailItem)insp.CurrentItem;
        }
        ...
        ...
        var selectedAttachments = (control.Context as AttachmentSelection)?.OfType<Attachment>();
        var attachments = selectedAttachments as IList<Attachment> ?? selectedAttachments.ToList();
                                
        foreach (var attachment in attachments)
        {
           // So here I know which attachments are selected. They have an index and a name.
           // I need to know which attachment this is in item.Attachments so I can remove the non-selected ones
           // and call the below line of code as normal. I can't find a way to associate the selected attachment
           // and the one in the MailItem.
           MyCustomCode.DoStuffWithAttachments(item);
        }
                   
}


I hope there is way to do this, as the alternative is going to be a lot of work...

Thanks,
Jeff
Posted 10 Aug, 2015 12:47:11 Top
Zach Jeyakaran




Posts: 120
Joined: 2011-09-07
Nevermind, I figured out that the index is the same order as the collection of attachments (probably where it gets seeded from). I just looped over them and I have a list of the selected ones (the ones I keep). Then I just removed what I needed from my object model.

-Jeff
Posted 10 Aug, 2015 16:05:48 Top
nwein




Posts: 577
Joined: 2011-03-28
Just an FYI, when dealing with COM objects you shouldn't use a foreach loop (and/or other linq variations) as the enumerator holds a reference to a COM object that is not released.
Even though uglier, for loops are your best friends w.r.t office add-ins. Here are some https://www.add-in-express.com/creating-addins-blog/2013/11/05/release-excel-com-objects/#foreach and more http://blogs.msdn.com/b/mstehle/archive/2007/12/07/oom-net-part-2-outlook-item-leaks.aspx
Posted 10 Aug, 2015 16:57:59 Top
Zach Jeyakaran




Posts: 120
Joined: 2011-09-07
Good to know. Thanks!
Posted 11 Aug, 2015 15:09:58 Top