Sample code for 30+ languages & platforms
DataFlex

Save All MIME Attachments to Files

See more MIME Examples

Demonstrates the Chilkat Mime.PartsToFiles method, which recursively traverses the MIME tree and saves each part having a nonempty filename parameter to a directory. The first argument is the destination directory and the second is a StringTable that receives the saved filenames.

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 extracts every named attachment from a message in one call, walking the whole tree so it finds attachments nested inside multipart containers. It saves only parts that declare a filename — inline body parts without one are skipped — and reports what it wrote via the StringTable, which is handy for logging or follow-up processing. The destination directory must already exist.

Chilkat DataFlex Downloads

DataFlex
Use ChilkatAx-win32.pkg

Procedure Test
    Boolean iSuccess
    Handle hoMime
    Variant vSavedFiles
    Handle hoSavedFiles
    Integer n
    Integer i
    String sName
    String sTemp1
    Boolean bTemp1

    Move False To iSuccess

    Get Create (RefClass(cComChilkatMime)) To hoMime
    If (Not(IsComObjectCreated(hoMime))) Begin
        Send CreateComObject of hoMime
    End
    Get ComLoadMimeFile Of hoMime "qa_data/multipart_message.eml" To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoMime To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    //  Recursively traverse the MIME tree and save each part that has a nonempty "filename" parameter
    //  to a directory.  The 1st argument is the destination directory and the 2nd is a StringTable
    //  that receives the saved filenames.
    Get Create (RefClass(cComChilkatStringTable)) To hoSavedFiles
    If (Not(IsComObjectCreated(hoSavedFiles))) Begin
        Send CreateComObject of hoSavedFiles
    End
    Get pvComObject of hoSavedFiles to vSavedFiles
    Get ComPartsToFiles Of hoMime "qa_output/attachments" vSavedFiles To iSuccess
    If (iSuccess = False) Begin
        Get ComLastErrorText Of hoMime To sTemp1
        Showln sTemp1
        Procedure_Return
    End

    Get ComCount Of hoSavedFiles To n
    Showln "Saved " n " files:"

    For i From 0 To (n - 1)
        Get ComStringAt Of hoSavedFiles i To sName
        Get ComLastMethodSuccess Of hoSavedFiles To bTemp1
        If (bTemp1 = False) Begin
            Get ComLastErrorText Of hoSavedFiles To sTemp1
            Showln sTemp1
            Procedure_Return
        End

        Showln sName
    Loop



End_Procedure