Outlook Interop - can't add attachment

  • Thread starter Thread starter LucaOrlandiniRMN
  • Start date Start date
L

LucaOrlandiniRMN

Guest
Hello,

we have a problem while trying to add an attachment to an email with Outlook Interop for Visual Basic .NET.

We are using Visual Studio 2017, Outlook 2016 and Microsoft.Office.Interop.Outlook version 15.0.4797.1003

This is the code:

' Create the Outlook application.
Dim outlookApp As New Outlook.Application()
' Create a new mail item.
Dim outlookMailItem = DirectCast(outlookApp.CreateItem(OlItemType.olMailItem), MailItem)
outlookMailItem.HTMLBody = "Test message"
'Add an attachment.
Dim displayNameForAttachment = "MyAttachment"
Dim position As Integer = CInt(outlookMailItem.Body.Length) + 1
Dim attachType = CInt(OlAttachmentType.olByValue)
outlookMailItem.Subject = "Test subject"
If IO.File.Exists(File) Then
Dim objattachments As Attachments = outlookMailItem.Attachments
Dim attach As Attachment
attach = objattachments.Add(File)
outlookMailItem.Attachments.Add(attach)
End If
outlookMailItem.Display()

Where "File" is a string with the full path of the file I am trying to attach, in this case as an example "C:\Test\testfile.txt"

The file exists in my computer, but when I try to add this to the Attachment with the "objattachments.Add" it gives an error: "Invalid file or directory name". I did also try with different files in different folders but I always have the same error.

Also, if I remove the attachment and open the email, I am able to drag and drop this "testfile.txt" in the email without any error.

I did try with different file in different paths but the error keeps showing. The mail will open with the correct subject and body but without attachment.

I believe this should be the correct way to add attachments. Is there another way? Or do I need to change the string or the format?

My purpose is to open an email with some text and one (or more) attachment, but without recipient.


Thanks,
Luca

Continue reading...
 
Back
Top