Search code examples
vbaoutlookrules

Automated Outlook Attachment Download with Email Date


I am hoping someone in here can help me with this request. I have found code shared by someone at https://www.pixelchef.net/content/rule-autosave-attachment-outlook that would help me setup a rule to automatically download attachments based on a rule.

The code is working fine but I want to tweak it to instead of naming the files like this 2021-08-28 10-00Test to format the name of the file like this Test_2021-08-28 10-00. The code is also at the moment adding the time stamp based on when the rule runs. I want to change it to instead pick up the date and time from the email.

Here is the code:

Public Sub saveAttachtoDisk(itm As Outlook.MailItem)
    Dim objAtt As Outlook.Attachment
    Dim saveFolder As String
    Dim dateFormat
    dateFormat = Format(Now, "yyyy-mm-dd H-mm")
    saveFolder = "C:\path"
    For Each objAtt In itm.Attachments
        objAtt.SaveAsFile saveFolder & "\" & dateFormat & objAtt.DisplayName
        Set objAtt = Nothing
    Next
End Sub

Any help is appreciated.


Solution

  • You can use the MailItem.ReceivedTime property which returns a Date indicating the date and time at which the item was received.

    Public Sub saveAttachtoDisk(itm As Outlook.MailItem)
        Dim objAtt As Outlook.Attachment
        Dim saveFolder As String
        Dim dateFormat
        dateFormat = Format(itm.ReceivedTime, "yyyy-mm-dd H-mm")
        saveFolder = "C:\path"
        For Each objAtt In itm.Attachments
            objAtt.SaveAsFile saveFolder & "\" & dateFormat & objAtt.DisplayName
            Set objAtt = Nothing
        Next
    End Sub
    

    There are two additional aspects I've noticed in your code:

    1. Your rule can process all kind of Outlook items - appointments, meeting requests, documents, mail and etc. So, it makes sense to add a type check to prevent any unexpected results when dealing with unsupported item types.
    2. Make sure the file name of the attached file has a unique name to save with. The folder can't contain two files with the same name while emails may contain two attachments with the same display name.