Search code examples
vbaoutlook

how to trigger a outlook macro for new mails from shared inbox


This code works perfectly for a normal inbox, but how to change the code to trigger an acknowledgement (only for new mails, need to exclude Re and Forward mails the comes to the inbox folder) from a shared mailbox ([email protected]).folder(inbox)

how to modify this code to trigger from a specific shared mailbox "Inbox"

Public WithEvents xlItems As Outlook.Items
        Private Sub Application_Startup()
        Set xlItems = Session.GetDefaultFolder(olFolderInbox).Items
        End Sub

Full Code:

Public WithEvents xlItems As Outlook.Items
    Private Sub Application_Startup()
    Set xlItems = Session.GetDefaultFolder(olFolderInbox).Items
    End Sub
    Private Sub xlItems_ItemAdd(ByVal objItem As Object)
    Dim xlReply As MailItem
    Dim xStr As String
    If objItem.Class <> olMail Then Exit Sub
    Set xlReply = objItem.Reply
    With xlReply
         xStr = "<p>" & "Hi Team, Acknowledging that we have received the Job. Thank you!" & "</p>"
         .HTMLBody = xStr & .HTMLBody
         .Send
    End With
End Sub

I tried Modifying the code but it did not work

Option Explicit
Private WithEvents olInboxItems As Items
  Dim objNS As NameSpace
  Set objNS = Application.Session
  ' instantiate objects declared WithEvents
  Set olInboxItems = objNS.Folders("[email protected]").Folders("Inbox").Items
  Set objNS = Nothing
End Sub

Private Sub olInboxItems_ItemAdd(ByVal Item As Object)
Dim xlReply As MailItem
Dim xStr As String
If objItem.Class <> olMail Then Exit Sub
Set xlReply = objItem.Reply
With xlReply
     xStr = "<p>" & "Hi Team, Acknowledging that we have received the Job. Thank you!" & "</p>"
     .HTMLBody = xStr & .HTMLBody
     .Send
End Sub

Solution

  • This should be more robust than checking for "Re: " and "Fw: " in the subject.

    In ThisOutlookSession

    Option Explicit ' Consider this mandatory
    ' Tools | Options | Editor tab
    ' Require Variable Declaration
    ' If desperate declare as Variant
    
    Public WithEvents olItems As Items
    
    Private Sub Application_Startup()
        
        Set olItems = Session.Folders("[email protected]").Folders("Inbox").Items
        
    End Sub
    
    Private Sub olItems_ItemAdd(ByVal Item As Object)
    
        Dim olReply As MailItem
     
        If Item.Class = olMail Then
            
            If Len(Item.ConversationIndex) > 44 Then
                Exit Sub
            
            Else
            
                Set olReply = Item.reply
        
                With olReply
                    .Body = "Reply to first email."
                    .Display
                End With
            
            End If
        
        End If
        
    End Sub