我的Outlook包含3个用户邮箱(缓存)和10个共享邮箱(在线)。
当发送其中任何一个邮箱中的邮件时我需要抓住,所以我用谷歌搜索我应该听“ItemAdd”事件。
问题是,没有触发ItemAdd事件。
这是我的测试代码:
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
知道为什么不解雇?
由于
答案 0 :(得分:0)
这对初学者来说是一个广为流传的错误......
您需要在全局范围内声明源对象(例如,在加载项类中)并保持活动状态以获取事件。或者垃圾收集器刷掉堆,源对象将被销毁。
在您的情况下,定义一个Outlook文件夹列表,您可以在其中保留所有引用。