Question

I'm working on project to check email attachment size and it notifies the sender when they are trying to attach a large document. I started by using example code shown at http://msdn.microsoft.com/en-us/library/office/aa209975(v=office.11).aspx and it works great as described when running the sub TestAttachAdd(). However, with the code running, when I manually create a new email and attach a file to it, the AttachmentAdd event is not triggered.

Am I using the private sub "newItem_AttachmentAdd" incorrectly for what I'm trying to do?

Or is there another Outlook event that I can use to detect when a user attaches a document (either using the "attach file" ribbon button or by drag-and-drop) to a new email?

Public WithEvents newItem As Outlook.MailItem

Private Sub newItem_AttachmentAdd(ByVal newAttachment As Attachment)
    If newAttachment.Type = olByValue Then
        newItem.Save
        If newItem.Size > 500 Then '500 bytes used for testing purposes only 
            MsgBox "Warning: Item size is now " & newItem.Size & " bytes."
        End If
    End If
End Sub

Public Sub TestAttachAdd()
    Dim olApp As New Outlook.Application
    Dim atts As Outlook.Attachments
    Dim newAttachment As Outlook.Attachment

    Set newItem = olApp.CreateItem(olMailItem)  
    newItem.Subject = "Test attachment"
    Set atts = newItem.Attachments
    Set newAttachment = atts.Add("C:\Test.txt", olByValue)
End Sub

-------------------------- updated with most current working version 1/27/2014

Public WithEvents goInspectors As outlook.Inspectors
Public WithEvents newItem As outlook.MailItem

Private Sub Initialize_Handlers()
    Set goInspectors = outlook.Application.Inspectors
End Sub

Private Sub Application_Startup()
    Initialize_Handlers
End Sub

Private Sub goInspectors_NewInspector(ByVal Inspector As Inspector)
    If Inspector.CurrentItem.Class = olMail Then
        Set newItem = Inspector.CurrentItem
    End If
End Sub

Private Sub newItem_AttachmentAdd(ByVal newAttachment As Attachment)
    If newAttachment.Type = olByValue Then
        newItem.Save
        If newItem.Size > 500 Then '500 bytes used for testing purposes only
            MsgBox "Warning: Item size is now " & newItem.Size & " bytes."
        End If
    End If
End Sub
Was it helpful?

Solution

You need to attach your event handler to the right MailItem object.

Trap the Application.Inspectors.NewInspector event, then retrieve the new item from Inspector.CurrentItem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top