Index Out of Bounds using mailItem.Attachments.Add

Viewed 38

We have created an outlook add in so that a user can press a button in Outlook and add a pdf file as an attachment automatically, to save them time having to try find it on the system

Tried different ways of using mailItem.Attachments.Add but they all seem to have the same problem

Private Sub OfficeAccount_Click(sender As Object, e As RibbonControlEventArgs) Handles OfficeAccount.Click

    Dim theAttachment = "http://webapps/Intranet/Home/Office/Documents/Template.pdf"

    Dim item = TryCast(Me.Context, Outlook.Inspector)
    Dim mailItem = TryCast(item.CurrentItem, Outlook.MailItem)

    mailItem.Attachments.Add(theAttachment, , , "Template")

    Marshal.ReleaseComObject(mailItem)

End Sub

It usually adds the attachment but sometimes it stops adding the attachment and says index out of bounds.

It then also stops allowing attachments to be added normally and has the same error message

1 Answers

The source of the attachment can be a file (represented by the full file system path with a file name) or an Outlook item that constitutes the attachment.

You need to download the file locally and then attach a file from your hard drive.

Sub AddAttachment() 
 Dim myItem As Outlook.MailItem 
 Dim myAttachments As Outlook.Attachments  
 Set myItem = Application.CreateItem(olMailItem) 
 Set myAttachments = myItem.Attachments 
 myAttachments.Add "C:\Test.doc", olByValue, 1, "Test" 
 myItem.Display 
End Sub
Related