Sample code for 30+ languages & platforms
PureBasic

Attach a File to a Multipart MIME Entity

See more MIME Examples

Demonstrates the Chilkat Mime.AppendPartFromFile method, which reads a local file, creates an attachment part, and appends it. The only argument is the file path; the content headers are chosen from the filename extension.

Note: The file paths are relative to the application's current working directory. Absolute paths may also be used. Supply the paths appropriate to your own environment.

Background: This is the one-call way to add an attachment: Chilkat reads the file, infers its Content-Type from the extension, base64-encodes binary content, and appends it as a child part — typically inside a multipart/mixed. It is the building block behind adding attachments to an email, saving you from constructing the part and setting its headers by hand.

Chilkat PureBasic Downloads

PureBasic
IncludeFile "CkMime.pb"

Procedure ChilkatExample()

    success.i = 0

    ;  Demonstrates the Mime.AppendPartFromFile method, which reads a local file, creates an attachment
    ;  part, and appends it.  The only argument is the file path; the content headers are chosen from
    ;  the filename extension.

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

    success = CkMime::ckNewMultipartMixed(mime)
    If success = 0
        Debug CkMime::ckLastErrorText(mime)
        CkMime::ckDispose(mime)
        ProcedureReturn
    EndIf

    ;  A message body part.
    bodyPart.i = CkMime::ckCreate()
    If bodyPart.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkMime::ckSetBodyFromPlainText(bodyPart,"Please see the attached files.")
    If success = 0
        Debug CkMime::ckLastErrorText(bodyPart)
        CkMime::ckDispose(mime)
        CkMime::ckDispose(bodyPart)
        ProcedureReturn
    EndIf

    success = CkMime::ckAppendPart(mime,bodyPart)
    If success = 0
        Debug CkMime::ckLastErrorText(mime)
        CkMime::ckDispose(mime)
        CkMime::ckDispose(bodyPart)
        ProcedureReturn
    EndIf

    ;  Attach files directly.
    success = CkMime::ckAppendPartFromFile(mime,"qa_data/report.pdf")
    If success = 0
        Debug CkMime::ckLastErrorText(mime)
        CkMime::ckDispose(mime)
        CkMime::ckDispose(bodyPart)
        ProcedureReturn
    EndIf

    success = CkMime::ckAppendPartFromFile(mime,"qa_data/photo.jpg")
    If success = 0
        Debug CkMime::ckLastErrorText(mime)
        CkMime::ckDispose(mime)
        CkMime::ckDispose(bodyPart)
        ProcedureReturn
    EndIf

    Debug "Number of parts: " + Str(CkMime::ckNumParts(mime))


    CkMime::ckDispose(mime)
    CkMime::ckDispose(bodyPart)


    ProcedureReturn
EndProcedure