0
votes

I use an existing script from this link: https://www.extendoffice.com/documents/outlook/3747-outlook-auto-download-save-attachments-to-folder.html to save all attachments in an email to a directory.

When an email containing two different files with the same name is received, one of the attachments is saved and one is overwritten.

I tried to check for an existing file and to add a number at the end of the next file. I removed that part of the script.

I attempted to add a randomly generated integer within the file name, along with a time stamp to make each file unique.

Current script is below:

Public Sub SaveAttachmentsToDisk(MItem As Outlook.MailItem)
Dim oAttachment As Outlook.Attachment
Dim sSaveFolder As String
Dim date_now As Date
Dim dateStamp As String
Dim LRandomNumber As Integer

LRandomNumber = Int((300 - 200 + 1) * Rnd + 200)
date_now = Now()
dateStamp = Format(date_now, "yyyy-mm-dd-hh-mm-ss")

sSaveFolder = "c:\filepath"
For Each oAttachment In MItem.Attachments
oAttachment.SaveAsFile sSaveFolder & dateStamp & LRandomNumber & oAttachment.DisplayName
Next
End Sub
1

1 Answers

0
votes

Add an additional unique identifier to the end of the dateStamp related to the sequence number of the attachment.

For Each oAttachment In MItem.Attachments
    oAttachment.SaveAsFile sSaveFolder & dateStamp & oAttachment.ID & LRandomNumber & oAttachment.DisplayName
Next

You could also be a little more controlling:

For iterator = 1 to MItem.Attachments.Count
        oAttachment.SaveAsFile sSaveFolder & dateStamp & iterator & LRandomNumber & oAttachment.DisplayName
Next

Of course, add this discriminator where most appropriate (could be after LRandomNumber)

Your issue with the random number is that you set it outside the loop, so each attachment is going to get the same number (set randomly earlier). In addition, there is no guarantee that the next random number is going to be different from the last (that is the thing about randomness - no guarantees). I suspect that, if you apply the method I have above, you won't need the random number.