如何使用 Outlook VBA 在收件箱中创建带有未读邮件数量的自动回复?

How to create autoreply with number of unread mails in inbox using Outlook VBA?

我正在尝试触发带有规则的脚本来发送自动回复。

“您好,感谢您的来信,您的邮件已放入队列中,您面前有 XX 封电子邮件,我们会尽快回复."

XX 应该是未读邮件的数量。

我找到了 outlook automated reply with unread message count:

Private Sub myOlItems_ItemAdd(ByVal Item As Object)

End Sub

Sub AutoResponse(objmsg As Outlook.MailItem)

    ' define my reply message
    Dim objReply As MailItem
    ' let's get ourselves the inbox!
    Dim inbox As MAPIFolder
    Set inbox = Application.GetNamespace("MAPI"). _
    GetDefaultFolder(olFolderInbox)

    ' Let's get this reply going!
    Set objReply = objmsg.Reply
    ' Subject Re: their subject. Standard
    objReply.Subject = "Re: " & objReply.Subject
    ' Body - you define this, use the variable for the unread count in inbox
    objReply.Body = "Your email has been received. I currently have " & inbox.UnReadItemCount & " unread emails in my inbox and I will get yours as soon as I can"

    ' Send this thing!
    objReply.Send
    ' Reset
    Set objReply = Nothing

End Sub

没用。

我在 Outlook 2016 上使用交换邮件服务器。

您需要在 Outlook 中手动创建规则并将 VBA 宏子 (AutoResponse) 分配给该规则。只有这样你才会得到代码运行。

作为一种可能的解决方法,您可以处理 NewMailEx event of the Application which is fired when a new item is received in the Inbox. The event fires when a new message arrives in the Inbox and before client rule processing occurs. You can use the Entry ID returned in the EntryIDCollection array to call the NameSpace.GetItemFromID method and process the item. See Outlook's Rules and Alerts: Run a Script 以获取更多信息。

对于拥有 Exchange Server 帐户(非缓存 Exchange 模式或缓存 Exchange 模式)的用户,只有在 Outlook 启动后到达服务器的邮件才会触发该事件。对于在 Outlook 启动后立即在缓存 Exchange 模式下同步的邮件,以及 Outlook 在非缓存 Exchange 模式下启动时已经在服务器上的邮件,不会触发该事件。

您的Items.ItemAdd Event设置不正确,请尝试没有Outlook规则的流畅代码,确保重新启动您的Outlook

Private WithEvents Items As Outlook.Items

Private Sub Application_Startup()
    Dim olNs As Outlook.NameSpace
    Dim Inbox  As Outlook.MAPIFolder

    Set olNs = Application.GetNamespace("MAPI")
    Set Inbox = olNs.GetDefaultFolder(olFolderInbox)
    Set Items = Inbox.Items
End Sub

Private Sub Items_ItemAdd(ByVal Item As Object)

    If TypeOf Item Is Outlook.mailitem Then
        AutoResponse Items
    End If

End Sub

Private Sub AutoResponse(Item As Outlook.mailitem)
    Dim Reply As Outlook.mailitem ' Reply msg
    Dim Inbox As Outlook.MAPIFolder ' Inbox

    Set Inbox = Application.GetNamespace("MAPI") _
                .GetDefaultFolder(olFolderInbox)

    ' Let's get this reply going!
    Set Reply = Item.Reply
    ' Subject Re: their subject. Standard
    Reply.subject = Reply.subject

    ' Body - you define this, use the variable for the unread count in inbox
    Reply.HTMLBody = "Your email has been received. I currently have " & _
                      Inbox.UnReadItemCount & _
              " unread emails in my inbox and I will get yours as soon as I can"

    ' Send this thing!
    Reply.Send
    ' Reset
    Set Reply = Nothing

End Sub