问题
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.
回答1:
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.
回答2:
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.
来源:https://stackoverflow.com/questions/49483298/why-does-attachments-count-return-0-on-incoming-mail-with-attachments