Sample code for 30+ languages & platforms
Xbase++

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 Xbase++ Downloads

Xbase++
LOCAL nSuccess
LOCAL oEmail
LOCAL oSbContentType
LOCAL nCaseSensitive
LOCAL nInlineOnly
LOCAL nExcludeAttachments
LOCAL cSearchSpec
LOCAL nNumParts
LOCAL i
LOCAL cTextBody
LOCAL oAttachedEmail
LOCAL oBdMime
LOCAL oBd

nSuccess := 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

oEmail := CreateObject("Chilkat.Email")

nSuccess := oEmail:LoadEml("qa_data/eml/sample.eml")
IF (nSuccess == 0)
    ? "Failed to load .eml"
    oEmail:destroy()
    RETURN
ENDIF

oSbContentType := CreateObject("Chilkat.StringBuilder")
nCaseSensitive := 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)
nInlineOnly := 0
nExcludeAttachments := 0
cSearchSpec := "*/*"

nNumParts := oEmail:GetNumPartsOfType(cSearchSpec, nInlineOnly, nExcludeAttachments)
i := 0
DO WHILE i < nNumParts
    //  What is the Content-Type of this MIME part?
    oSbContentType:Append(oEmail:GetNthContentType(i, cSearchSpec, nInlineOnly, nExcludeAttachments))
    IF (oSbContentType:StartsWith("text/", nCaseSensitive) == 1)
        //  Get the text body of this MIME part.
        cTextBody := oEmail:GetNthTextPartOfType(i, cSearchSpec, nInlineOnly, nExcludeAttachments)
        ? "Got text body for " + oSbContentType:GetAsString()
    ELSE
        IF (oSbContentType:ContentsEqual("message/rfc822", nCaseSensitive) == 1)
            //  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...
            oAttachedEmail := CreateObject("Chilkat.Email")
            oBdMime := CreateObject("Chilkat.BinData")
            oEmail:GetNthBinaryPartOfTypeBd(i, cSearchSpec, nInlineOnly, nExcludeAttachments, oBdMime)
            oAttachedEmail:SetFromMimeBd(oBdMime)
            //  Now your app can recursively process the attachedEmail...
        ELSE
            //  Get the bytes of this MIME body part.
            oBd := CreateObject("Chilkat.BinData")
            oEmail:GetNthBinaryPartOfTypeBd(i, cSearchSpec, nInlineOnly, nExcludeAttachments, oBd)
            ? "Got binary body for " + oSbContentType:GetAsString() + " numBytes = " + Str(oBd:NumBytes)
        ENDIF

    ENDIF

    oSbContentType:Clear()
    i := i + 1
ENDDO

oEmail:destroy()
oSbContentType:destroy()
oAttachedEmail:destroy()
oBdMime:destroy()
oBd:destroy()