Sample code for 30+ languages & platforms
Tcl

Iterate MIME Parts of an Email

See more Email Object Examples

Demonstrates how to iterate over the MIME sub-parts of an email, and retrieve the content of each MIME sub-part body.

Note: This example requires some new features added to Chilkat v9.5.0.95.

Chilkat Tcl Downloads

Tcl

load ./chilkat.dll

set success 0

# This example assumes the Chilkat API to have been previously unlocked.
# See Global Unlock Sample for sample code.

# See the following Chilkat post to Quickly Understand Email MIME

set email [new_CkEmail]

set success [CkEmail_LoadEml $email "qa_data/eml/sample.eml"]
if {$success == 0} then {
    puts "Failed to load .eml"
    delete_CkEmail $email
    exit
}

set sbContentType [new_CkStringBuilder]

set caseSensitive 0

# Get the total number of non-multipart MIME sub-parts.
# (This is a simple way of iterating over all the MIME leaf parts regardless of the MIME tree structure)
set inlineOnly 0
set excludeAttachments 0
set searchSpec "*/*"

set numParts [CkEmail_GetNumPartsOfType $email $searchSpec $inlineOnly $excludeAttachments]
set i 0
while {$i < $numParts} {
    # What is the Content-Type of this MIME part?
    CkStringBuilder_Append $sbContentType [CkEmail_getNthContentType $email $i $searchSpec $inlineOnly $excludeAttachments]
    if {[CkStringBuilder_StartsWith $sbContentType "text/" $caseSensitive] == 1} then {
        # Get the text body of this MIME part.
        set textBody [CkEmail_getNthTextPartOfType $email $i $searchSpec $inlineOnly $excludeAttachments]
        puts "Got text body for [CkStringBuilder_getAsString $sbContentType]"
    }     else {
        if {[CkStringBuilder_ContentsEqual $sbContentType "message/rfc822" $caseSensitive] == 1} then {
            # If the Content-Type is message/rfc822, then the MIME body for this part contains a full embedded MIME messages.
            # Your application could load it into a Chilkat email object and recursively process...
            set attachedEmail [new_CkEmail]

            set bdMime [new_CkBinData]

            CkEmail_GetNthBinaryPartOfTypeBd $email $i $searchSpec $inlineOnly $excludeAttachments $bdMime
            CkEmail_SetFromMimeBd $attachedEmail $bdMime
            # Now your app can recursively process the attachedEmail...
        }         else {
            # Get the bytes of this MIME body part.
            set bd [new_CkBinData]

            CkEmail_GetNthBinaryPartOfTypeBd $email $i $searchSpec $inlineOnly $excludeAttachments $bd
            puts "Got binary body for [CkStringBuilder_getAsString $sbContentType] numBytes = [CkBinData_get_NumBytes $bd]"
        }

    }

    CkStringBuilder_Clear $sbContentType
    set i [expr $i + 1]
}

delete_CkEmail $email
delete_CkStringBuilder $sbContentType
delete_CkEmail $attachedEmail
delete_CkBinData $bdMime
delete_CkBinData $bd