vbaoutlookoffice365email-attachments

Download attachment and rename with subject line


I am using Office 365.

This code works.

Public Sub saveAttachtoDisk(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
saveFolder = "C:\Users\ppp\Desktop\Image Test"
    
For Each objAtt In itm.Attachments
    objAtt.SaveAsFile saveFolder & "" & objAtt.DisplayName
    Set objAtt = Nothing
Next
End Sub

I want to amend it to save pdf attachments with the subject of the email.

The file is saved as type: file (not PDF) and size is 0 KB.
Additionally it saves the file with the name of the attachment not the subject.

Public Sub saveAttachtoDisk(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
Dim saveFolder As String
saveFolder = "C:\Users\ppp\Desktop\Image Test"
MSN = Trim(itm.Subject)

For Each objAtt In itm.Attachments
    objAtt.SaveAsFile saveFolder & "" & itm.Subject & ".PDF"
    Set objAtt = Nothing
Next 
End Sub

Solution

  • First, you need to use unique names for files saved to the disk. In the following code the subject property is used for all attachments:

    For Each objAtt In itm.Attachments
      objAtt.SaveAsFile saveFolder & "" & itm.Subject & ".PDF"
      Set objAtt = Nothing
    Next 
    

    So, you need to add a unique ID to the file name to be able to have them all on the disk. Otherwise, the same file with the Subject name will be overwritten.

    Second, make sure that file name passed to the SaveAsFile method doesn't contain forbidden symbols. See Remove illegal characters while saving workbook Excel VBA for more information.

    Third, make sure that you pass a valid file path to the SaveAsFile method. I'd recommend adding the Debug.Print statement which could help to identify possible issues with a file path. Just try to print the result file path string to the console and see whether it was built correctly or not.