0
votes

I'm trying to save attachments automatically to a local folder using Outlook 2010.

It works when I first create the rule and apply it to all inbox. It doesn't work with incoming mail (no file was saved).

I tried adding some weird code and it fired errors so the script ran.

Public Sub saveAttachtoDisk(itm As Outlook.MailItem)

Dim objAtt As Outlook.Attachment
Dim saveFolder As String
    saveFolder = "C:\temp"
Dim dateFormat As String
    dateFormat = Format(itm.ReceivedTime, "yyyy-mm-dd Hmm ")
For Each objAtt In itm.Attachments
    objAtt.SaveAsFile saveFolder & "\" & dateFormat & objAtt.DisplayName
Next

End Sub

It seems that Outlook doesn't recognize the attachment for incoming mail. I tried adding "MsgBox MyMail.Attachments.Count" and it returned 0.

2
This is just function. How you call this function?Rahul
I added a rule in Outlook to call this function when new mails come. I followed instruction from this site extendoffice.com/documents/outlook/…Nguyễn Hữu Bảo Kiên
Is this your first vba code on outlook?0m3r
Yes, it is.I just started using Outlook last week. I also have another function to save incoming mail's details to excel file and it works just fine.Nguyễn Hữu Bảo Kiên
I don't see any issues on your code, try deleting the rule and recreate- also make sure your macro security setting is okay to run your code0m3r

2 Answers

0
votes

Replace your Outlook Rule with Items.ItemAdd Event (Outlook) see example

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
        saveAttachtoDisk Item ' call sub
    End If
End Sub

Application.Startup Event (Outlook) and Items.ItemAdd Event (Outlook)


Items.ItemAdd Event (Outlook) Occurs when one or more items are added to the specified collection. This event does not run when a large number of items are added to the folder at once. This event is not available in Microsoft Visual Basic Scripting Edition (VBScript).


Application.Startup Event (Outlook) Occurs when Microsoft Outlook is starting, but after all add-in programs have been loaded.


0
votes

I finally found out the reason. It seems that using IMAP is not an option if I want to save attachments automatically. I switched to POP3 and everything works just fine.