Reputation: 61
I have developed a VSTO plug-in. We have hooked the ItemSend event in our code. When I try to send mail, I am trying to remove all attachments before sending it. However mail is still having all attachments which were removed. I can see them in send folder as well as in inbox.
Strange thing is that when I print count for number of attachments, it is giving 0. But when I print mime using MAPI object and APIs, it is still showing attachment there. It seems that MailItem object of OOM is not in synch with MAPI object.
Is there any way to enforce this synchronization.
I have written following code --
int numOfAttachments = mailItem.Attachments.Count;
for (int index = numOfAttachments; index > 0; --index)
{
Attachment attachment = mailItem.Attachments[index];
attachment.Delete();
Marshal.ReleaseComObject(attachment);
}
PrintInfo("Attachment count - " +
mailItem.Attachments.Count.ToString());
mailItem.Save();
string mimeSource = MimeParser.GetMimeSource(mailItem);
File.WriteAllText("C:\\Test\\Mime2.txt", mimeSource);
Marshal.ReleaseComObject(mailItem);
return;
Upvotes: 0
Views: 170
Reputation: 49395
I guess the Attachments.Remove method leads to same results, right?
First of all, I'd recommend releasing all underlying COM objects instantly. For example:
int numOfAttachments = mailItem.Attachments.Count;
The Attachments
property returns an instance of the Attachments
collection which is left alive. You need to release only objects you get from the Outlook object model via properties and methods. Use System.Runtime.InteropServices.Marshal.ReleaseComObject
to release an Outlook object when you have finished using it. Then set a variable to Nothing
in Visual Basic (null
in C#) to release the reference to the object. You can read more about this in the Systematically Releasing Objects article in MSDN.
Finally, the ItemSend
event handler allows to cancel the default action by setting the cancel parameter to true. So, you could do any modifications and send submit the mail item anew.
Upvotes: 1