0
votes

I am developing an Addin for outlook 2013. It is a sample project and what I want to do is to remove all attachments from mailitem. This is how i do it

while (mail.Attachments.Count > 0)
 {
    try
    {
      mail.Attachments.Remove(1);
     }
       catch(Exception e)
     {
        MessageBox.Show(e.Message);
     }

 }

Edit: I have also tried the way to remove them with an inverted for loop(for i = mail.Attachments.Count; i > 1; i--) but got same result

And it works fine except for the fact that it throws this exception on console:

Exception thrown: 'System.Runtime.InteropServices.COMException' in PCMailAddIn.dll

Exception thrown: 'System.Reflection.TargetInvocationException' in mscorlib.dll

2

2 Answers

0
votes
// Remove all attachments

var allIndexesList = mailItem.Attachments.Cast<Outlook.Attachment>().ToList();

var descIndexes = allIndexesList.Select(a => a.Index).OrderByDescending(i => i).ToArray();


foreach(var i in indexes)
{
    try
    {
        mailItem.Attachments.Remove(i);
    }
    catch (COMException e)
    {
        MessageBox.Show(e.Message);
    }
}
0
votes

You can access each attachment and than remove object at that index. Try this: // Remove all attachments var attachments = mailItem.Attachments.Cast().ToList(); if (attachments.Any()) { attachments.Reverse(); attachments.ForEach(att => mailItem.Attachments.Remove(att.Index)); }