Home > Software engineering >  How to create an outlook attachment in-memory using VBA
How to create an outlook attachment in-memory using VBA

Time:12-02

I am using VBA to send an email with text attachment. Until now, I needed to physically create the file on the disk and afterwards reference its path.

Can this be done completely in mem?

    Dim outlook As Object, mail As Object, path As string

    Set outlook = CreateObject("Outlook.Application")
    Set mail = outlook.CreateItem(0)

    ' write file contents
    path = Environ("temp")   "\file.txt"
    Open path For Output As #1
    Print #1, "This is my txt"
    Close #1

    ' attach file
    With mail
        .To = "[email protected]"
        .body = "This is a test"
        .attachments.Add CStr(path)
        .send
    End With

    Set mail = Nothing
    Set outlook = Nothing

CodePudding user response:

The Outlook object model doesn't provide any property or method for that. The Add method of the Attachments class accepts a file path only. More precisely, 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.

However, you can use a low-level API - Extended MAPI on which Outlook is built. Or consider any third-party wrappers around this API such as Redemption. The PR_ATTACH_DATA_BIN contains binary attachment data typically accessed through the Object Linking and Embedding (OLE) IStream interface. This property holds the attachment when the value of the PR_ATTACH_METHOD (PidTagAttachMethod) property is ATTACH_BY_VALUE, which is the usual attachment method and the only one required to be supported.

  • Related