'Use VBA to Change the Name of Specific Attachment when the Send Button it Hit

Using Microsoft Outlook, I am trying to change the name of a specific attachment when the user clicks the "Send" button in a new outlook email.

If an attachment with the name is found then it will change that attachment's name to the subject of the email.

In the example below, I am using "form.pdf" as the target attachment.

When I run the code and try to change the DisplayName it doesn't change the name of the actual attachment in the email. Any Advice?

Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
    Dim myAttachments As Outlook.Attachments
    Set myAttachments = Item.Attachments

    For Each objAtt In myAttachments  

        If LCase(objAtt.DisplayName) = "form.pdf" Then
            objAtt.DisplayName = Item.Subject & ".pdf"
        End If

    Next
End Sub


Solution 1:[1]

Attachment.DisplayName property does absolutely nothing since Outlook 2002 - this is done for security purposes to prevent people from showing Evil.exe as ReadMe.txt. And Attachment.FileName property is read-only.

In theory, all need to need to do is set the PR_ATTACH_LONG_FILENAME property (DASL name http://schemas.microsoft.com/mapi/proptag/0x3707001F), but Outlook will raise an exception if you use Attachment.PropertyAccessor.SetProperty to set PR_ATTACH_LONG_FILENAME.

You can use Extended MAPI to set the property, but it is only accessible in C++ or Delphi, not in VBA or any .Net languages. You can use Redemption (I am its author) to set it in VBA or any .Net language:

set rSession = CreateObject("Redemption.RDOSession")
rSession.MAPIOBJECT = Application.Session.MAPIOBJECT
Item.Save
set rItem = rSession.GetRDOObjectFromOutlookObject(Item)
set attach = rItem.Attachments(1)
'PR_ATTACH_LONG_FILENAME_W
attach.Fields("http://schemas.microsoft.com/mapi/proptag/0x3707001F") = "whatever.pdf"
'PR_ATTACH_FILENAME_W
attach.Fields("http://schemas.microsoft.com/mapi/proptag/0x3704001F") = "whatever.pdf"
'PR_DISPLAY_NAME_W
attach.Fields("http://schemas.microsoft.com/mapi/proptag/0x3001001F") = "whatever.pdf"
rItem.Save

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1