使用NewMailEx处理一个帐户,其中有多个帐户

时间:2017-04-29 14:03:49

标签: vba outlook outlook-vba

在MS Outlook中有两个帐户。对于大多数收到的电子邮件,这两个帐户会收到相同的电子邮件,有时会收到CC或TO字段。这两个帐户类似,并且具有几乎相同的子文件夹。

如果向两个帐户发送电子邮件,Application_NewMailEX会触发两次。

我只需要处理一个帐户(收件箱文件夹及其子文件夹),而不是第二个帐户。

我的目的是只执行一次NewMailEx子代码中的代码,并且仅针对在Outlook中设置的两个电子邮件帐户中的一个而不是另一个。

某些作业之后的代码会在SQL Server数据库中插入一些值。

类似的东西:

Private Sub Application_NewMailEx(ByVal EntryIDCollection As String)
    Dim arr()       As String
    Dim NS          As Outlook.NameSpace
    Dim itm         As MailItem
    Dim m           As Outlook.MailItem
    Dim i           as Integer
    On Error Resume Next
    arr = Split(EntryIDCollection, ",")
    For i = 0 To UBound(arr)
        Set itm = NS.GetItemFromID(arr(i))        
        If itm.Class = olMail Then
            Set m = itm               
            ' Filter 
            If m.Sender = "Our Client" and Trim(m.Subject) = "12 AXR check" then            
                ' operations
                '....           
                ' Insert DB
                '....
            End If        
            ' Other things
        End If
    Next
End Sub

2 个答案:

答案 0 :(得分:1)

如果不理解为什么会出现重复,我建议您先验证收件箱。

Option Explicit

Private Sub Application_NewMailEx(ByVal EntryIDCollection As String)

Dim arr() As String
Dim NS As Outlook.NameSpace

'Dim itm As Mailitem
Dim itm As Object               ' <---

Dim m As Outlook.mailitem
Dim i As Integer

'On Error Resume Next
' If you need this determine the exact place then
'  turn error bypass off as soon as possible with
'On Error GoTo 0

Set NS = GetNamespace("MAPI")

arr = Split(EntryIDCollection, ",")

For i = 0 To UBound(arr)

    Set itm = NS.GetItemFromID(arr(i))

    If itm.Class = olMail Then

        Set m = itm

        Debug.Print "mail received"
        Debug.Print itm.Parent.Parent.name

        If itm.Parent.Parent.name = "someone@somewhere.com" Then
            ' operations
            Debug.Print " item in my inbox processed"

        Else
            Debug.Print " item in any other inbox not processed"

        End If

    End If

Next

End Sub

答案 1 :(得分:1)

<强>更新

我只进行了一些小改动及其工作

If InStr(1, LCase(itm.Parent.Parent.FolderPath), "sharingaccount@123.abc") > 0 Then
   Debug.Print "OK"
End If

我使用了该代码,因为我有一个结构,对于帐户,如下所示,我只想处理SharingAccount及其subfolder中的传入电子邮件:

MyPersonalMail@123.abc
   Inbox
      Documents
      FromLinux
      FromAra

SharingAccount@123.abc
   Inbox
      Documents
      FromLinux
      FromAra

由于