Sample code for 30+ languages & platforms
DataFlex

Get an Attachment's Bytes into a BinData

See more Email Object Examples

Demonstrates the Chilkat Email.GetAttachmentBd method, which copies an attachment's binary data into a BinData object. The first attachment is at index 0. This example adds an attachment and copies its bytes into a BinData, printing the byte count.

Background: This is the safe, binary way to extract an attachment — the counterpart to the text-oriented GetAttachmentString. Because attachments are often binary (PDFs, images, archives), copying the raw bytes into a BinData preserves them exactly, ready to write to a file, hash, or pass to another API without any charset conversion that could corrupt the data.

Chilkat DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoEmail
    Variant vBd
    Handle hoBd
    String sTemp1
    Integer iTemp1

    Move False To iSuccess

    //  Demonstrates the GetAttachmentBd method, which copies an attachment's binary data into a
    //  BinData object.  The first attachment is at index 0.

    Get Create (RefClass(cComChilkatEmail)) To hoEmail
    If (Not(IsComObjectCreated(hoEmail))) Begin
        Send CreateComObject of hoEmail
    End
    Set ComSubject Of hoEmail To "GetAttachmentBd example"

    Get ComAddStringAttachment Of hoEmail "notes.txt" "Some notes stored in the attachment." To iSuccess

    //  Copy the first attachment's binary data into a BinData object.
    Get Create (RefClass(cComChilkatBinData)) To hoBd
    If (Not(IsComObjectCreated(hoBd))) Begin
        Send CreateComObject of hoBd
    End
    Get pvComObject of hoBd to vBd
    Get ComGetAttachmentBd Of hoEmail 0 vBd To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoEmail To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Get ComNumBytes Of hoBd To iTemp1
    Showln "Attachment size (bytes) = " iTemp1


End_Procedure