Search code examples
vbaoutlookemail-attachments

How to invoke code when there is incoming mail?


I have VBA code to download attachment immediately after mail comes into Outlook.

How do I invoke this code or is there another way to download attachments automatically?

Sub saveAttachtoDisk(itm As Outlook.MailItem)
    Dim saveFolder As String
    saveFolder = "D:\outlook\"
    For Each objAtt In itm.Attachments
        MsgBox objAtt
        objAtt.SaveAsFile saveFolder & "\" & objAtt.DisplayName
        MsgBox saveFolder & "\" & objAtt.DisplayName
        Set objAtt = Nothing
    Next
End Sub

Solution

  • It looks like you are trying to create a rule which triggers a VBA script for saving attachments on the disk. If so, I'd recommend removing any MsgBox statements from the code. It may stop the code from running. Instead, you may use the Debug.Print statements in the code. See Where does VBA Debug.Print log to? for more information.

    Instead of using rules you may consider handling the NewMailEx event of the Application class. The event fires once for every received item that is processed by Microsoft Outlook. The item can be one of several different item types, for example, MailItem, MeetingItem, or SharingItem. The EntryIDsCollection string contains the Entry ID that corresponds to that item.

    Finally, you may find the Getting Started with VBA in Outlook 2010 article helpful.