Search code examples
c#outlookcomms-officeoutlook-addin

Add attachements event Outlook AddIn


I try to get the attachement file in an outlook plugin before the file attache to a the mailItem.

    private void Inspectors_NewInspector(Outlook.Inspector Inspector)
        {

            if (Inspector.CurrentItem is Outlook.MailItem)
            {

    Outlook.MailItem mail = (Outlook.MailItem)Inspector.CurrentItem;
                    Inspector.AttachmentSelectionChange += Inspector_AttachmentSelectionChange;
                    Application.AttachmentContextMenuDisplay += Application_AttachmentContextMenuDisplay;
                    mail.BeforeAttachmentAdd += Mail_BeforeAttachmentAdd;
                    mail.AttachmentAdd += Mail_AttachmentAdd;
                    mail.BeforeAttachmentWriteToTempFile += Mail_BeforeAttachmentWriteToTempFile;
                    mail.BeforeAttachmentSave += Mail_BeforeAttachmentSave;
}}

When i create a new Email in outlook, my code passe by this method, but the event is never fired when i add an attachement to my email.

Any idea ?


Solution

  • You need to declare the source object at the class level (global scope) to prevent it from dwiping by the garbage collector, for example:

        Outlook.MailItem mail = null;
        Outlook.Inspector inspector = null;
    
        private void Inspectors_NewInspector(Outlook.Inspector Inspector)
        {
            inspector = Inspector;
            object oMail = inspector.CurrentItem;
            if (oMail is Outlook.MailItem)
            {
    
                    mail = (Outlook.MailItem)oMail.CurrentItem;               
                    inspector.AttachmentSelectionChange += Inspector_AttachmentSelectionChange;
                    Application.AttachmentContextMenuDisplay += Application_AttachmentContextMenuDisplay;
                    mail.BeforeAttachmentAdd += Mail_BeforeAttachmentAdd;
                    mail.AttachmentAdd += Mail_AttachmentAdd;
                    mail.BeforeAttachmentWriteToTempFile += Mail_BeforeAttachmentWriteToTempFile;
                    mail.BeforeAttachmentSave += Mail_BeforeAttachmentSave;
            }
        }