vbaemailoutlookoutlook-2016

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


I am trying to trigger a script with rules to send an autoreply.

"Hi thanks for your mail, your mail has been placed in a queue there are XX number of e-mails in front of you, we will answer as soon as possible."

The XX should be the number of unread e-mails.

I found 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

It doesn't work.

I am on Outlook 2016, with an exchange mail server.


Solution

  • Your Items.ItemAdd Event is not set correctly, Try the flowing code without Outlook rule, Make sure to restart your 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