Sample code for 30+ languages & platforms
DataFlex

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

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoMime
    Variant vBodyPart
    Handle hoBodyPart
    String sTemp1
    Integer iTemp1

    Move False To iSuccess

    //  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.

    Get Create (RefClass(cComChilkatMime)) To hoMime
    If (Not(IsComObjectCreated(hoMime))) Begin
        Send CreateComObject of hoMime
    End
    Get ComNewMultipartMixed Of hoMime To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoMime To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    //  A message body part.
    Get Create (RefClass(cComChilkatMime)) To hoBodyPart
    If (Not(IsComObjectCreated(hoBodyPart))) Begin
        Send CreateComObject of hoBodyPart
    End
    Get ComSetBodyFromPlainText Of hoBodyPart "Please see the attached files." To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoBodyPart To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Get pvComObject of hoBodyPart to vBodyPart
    Get ComAppendPart Of hoMime vBodyPart To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoMime To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    //  Attach files directly.
    Get ComAppendPartFromFile Of hoMime "qa_data/report.pdf" To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoMime To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Get ComAppendPartFromFile Of hoMime "qa_data/photo.jpg" To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoMime To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Get ComNumParts Of hoMime To iTemp1
    Showln "Number of parts: " iTemp1


End_Procedure