MojoDK
MojoDK

Reputation: 4528

How do I listen to "ItemAdd" for all my "Sent items" folders?

My Outlook consists of 3 user mailboxes (cached) and 10 shared mailboxes (online).

I need to catch when a mail in either of these mailboxes is sent, so I googled that I should listen to "ItemAdd" event.

Problem is, that ItemAdd event is not fired.

Here's my test code:

Imports System.Runtime.InteropServices

Public Class ThisAddIn

    Private sentFolders As New List(Of Outlook.Folder)


    Private Sub ThisAddIn_Startup() Handles Me.Startup
        Call InitSentFolders()
    End Sub


    Private Sub ThisAddIn_Shutdown() Handles Me.Shutdown
    End Sub


    Private Sub InitSentFolders()
        Dim ns As Outlook.NameSpace = Application.GetNamespace("MAPI")
        Dim stores As Outlook.Stores = ns.Stores
        For i As Integer = 1 To stores.Count
            Try
                Dim store As Outlook.Store = stores(i)
                Try
                    Dim sentFolder As Outlook.Folder = TryCast(store.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderSentMail), Outlook.Folder)
                    AddHandler DirectCast(sentFolder.Items, Outlook.Items).ItemAdd, AddressOf ItemAdd
                    sentFolders.Add(sentFolder)
                Catch ex As Exception
                End Try
                Marshal.ReleaseComObject(store)
            Catch ex As Exception
            End Try
        Next
        Marshal.ReleaseComObject(stores)
        Marshal.ReleaseComObject(ns)
    End Sub


    Private Sub ItemAdd(ByVal ItemObject As Object)
        If TypeOf (ItemObject) Is Outlook.MailItem Then
            Dim item As Outlook.MailItem = CType(ItemObject, Outlook.MailItem)
            MsgBox(item.Sender.ToString)
            Marshal.ReleaseComObject(item)
        End If
    End Sub

End Class

Any idea why it is not fired?

Thanks

Upvotes: 2

Views: 308

Answers (1)

Eugene Astafiev
Eugene Astafiev

Reputation: 49395

That is a widely spread mistake for beginners...

You need declare the source object at the global scope (for example, at the add-in class) and keep it alive to get the event. Or the garbage collector swipes the heap and source object will be destroyed.

In your case define a list of Outlook folders where you can keep all references.

Upvotes: 2

Related Questions