Sample code for 30+ languages & platforms
PureBasic

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

PureBasic
IncludeFile "CkStringTable.pb"
IncludeFile "CkMime.pb"

Procedure ChilkatExample()

    success.i = 0

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

    success = CkMime::ckLoadMimeFile(mime,"qa_data/multipart_message.eml")
    If success = 0
        Debug CkMime::ckLastErrorText(mime)
        CkMime::ckDispose(mime)
        ProcedureReturn
    EndIf

    ;  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.
    savedFiles.i = CkStringTable::ckCreate()
    If savedFiles.i = 0
        Debug "Failed to create object."
        ProcedureReturn
    EndIf

    success = CkMime::ckPartsToFiles(mime,"qa_output/attachments",savedFiles)
    If success = 0
        Debug CkMime::ckLastErrorText(mime)
        CkMime::ckDispose(mime)
        CkStringTable::ckDispose(savedFiles)
        ProcedureReturn
    EndIf

    n.i = CkStringTable::ckCount(savedFiles)
    Debug "Saved " + Str(n) + " files:"
    i.i
    For i = 0 To n - 1
        name.s = CkStringTable::ckStringAt(savedFiles,i)
        If CkStringTable::ckLastMethodSuccess(savedFiles) = 0
            Debug CkStringTable::ckLastErrorText(savedFiles)
            CkMime::ckDispose(mime)
            CkStringTable::ckDispose(savedFiles)
            ProcedureReturn
        EndIf

        Debug name
    Next


    CkMime::ckDispose(mime)
    CkStringTable::ckDispose(savedFiles)


    ProcedureReturn
EndProcedure