Sample code for 30+ languages & platforms
PureBasic

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 PureBasic Downloads

PureBasic
IncludeFile "CkBinData.pb"
IncludeFile "CkEmail.pb"

Procedure ChilkatExample()

    success.i = 0

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

    email.i = CkEmail::ckCreate()
    If email.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    CkEmail::setCkSubject(email, "GetAttachmentBd example")

    CkEmail::ckAddStringAttachment(email,"notes.txt","Some notes stored in the attachment.")

    ;  Copy the first attachment's binary data into a BinData object.
    bd.i = CkBinData::ckCreate()
    If bd.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkEmail::ckGetAttachmentBd(email,0,bd)
    If success = 0
        Debug CkEmail::ckLastErrorText(email)
        CkEmail::ckDispose(email)
        CkBinData::ckDispose(bd)
        ProcedureReturn
    EndIf

    Debug "Attachment size (bytes) = " + Str(CkBinData::ckNumBytes(bd))


    CkEmail::ckDispose(email)
    CkBinData::ckDispose(bd)


    ProcedureReturn
EndProcedure