objItems_ItemAdd不会在将项目添加到olItems中时触发:如何应用ItemAdd事件?

问题描述 投票:0回答:1

我想为Outlook 2010中的传入电子邮件设置自动类别,但是我的代码不起作用。

我多次重新启动Outlook。

Public WithEvents olItems As Outlook.Items

Private Sub Application_Startup()
Set objItems = Outlook.Application.Session.GetDefaultFolder(olFolderInbox).Items
End Sub

Private Sub objItems_ItemAdd(ByVal Item As Object)
Dim objMail As Outlook.MailItem
Dim strSenderEmailAddress As String
Dim objContacts As Outlook.Items
Dim objContact As Object
Dim objFoundContact As Outlook.ContactItem
Dim strFilter As String
Dim strContactCategory As String
Dim i As Long

If TypeOf Item Is MailItem Then
    Set objMail = Item
    strSenderEmailAddress = objMail.SenderEmailAddress
    Set objContacts = 
 Outlook.Application.Session.GetDefaultFolder(olFolderContacts).Items
    For Each objContact In objContacts
        If TypeOf objContact Is ContactItem Then
            For i = 1 To 3
                strFilter = "[Email" & i & "Address] = " & 
 strSenderEmailAddress
                Set objFoundContact = objContacts.Find(strFilter)
                'Check if the sender exists in your contacts folder
                If Not (objFoundContact Is Nothing) Then
                    strContactCategory = objFoundContact.Categories
                    'If the corresponding contact has no category
                    'Assign the "Known" category to the email
                    If strContactCategory = "" Then
                        objMail.Categories = "Known"
                        'If the contact has, directly use its category
                        Else
                            objMail.Categories = strContactCategory
                     End If
                     Exit For
                End If
            Next i

            'If the sender doesn't exist in the Contacts folder
            'Assign the "Unknown" category to the email
            If objFoundContact Is Nothing Then
                objMail.Categories = "Unknown"
            End If
        End If
    Next objContact
End If
End Sub

我在VBA中不擅长。当新电子邮件到达我的邮箱时,它不会自动分类,Outlook中的“类别”字段中没有颜色填充,什么也没有发生。

outlook-vba
1个回答
0
投票

我想为Outlook 2010中的传入电子邮件设置自动类别,但是我的代码不起作用。

首先,您需要处理收件箱中收到新项目时触发的Application类的NewMailEx事件。

[NewMailEx事件在新消息到达收件箱时并且在客户端规则处理之前触发。您可以使用EntryIDCollection数组中返回的Entry ID来调用NameSpace.GetItemFromID方法并处理该项目。请谨慎使用此方法,以最小化对Outlook性能的影响。但是,根据客户端计算机上的设置,新邮件到达收件箱后,垃圾邮件过滤和将新邮件从收件箱移动到另一个文件夹的客户端规则等过程可能会异步发生。

收到项目后,您可以设置一个类别。

P.S。如果您同时收到十六个以上的项目,则可能根本不会触发ItemAdd事件。这是Outlook对象模型中的已知问题。

© www.soinside.com 2019 - 2024. All rights reserved.