Sample code for 30+ languages & platforms
AutoIt

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

AutoIt
Local $bSuccess = False

; 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 = ObjCreate("Chilkat.Email")

$bSuccess = $oEmail.LoadEml("qa_data/eml/sample.eml")
If ($bSuccess = False) Then
    ConsoleWrite("Failed to load .eml" & @CRLF)
    Exit
EndIf

$oSbContentType = ObjCreate("Chilkat.StringBuilder")
Local $bCaseSensitive = False

; 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)
Local $bInlineOnly = False
Local $bExcludeAttachments = False
Local $searchSpec = "*/*"

Local $iNumParts = $oEmail.GetNumPartsOfType($searchSpec,$bInlineOnly,$bExcludeAttachments)
Local $i = 0
While $i < $iNumParts
    ; What is the Content-Type of this MIME part?
    $oSbContentType.Append($oEmail.GetNthContentType($i,$searchSpec,$bInlineOnly,$bExcludeAttachments))
    If ($oSbContentType.StartsWith("text/",$bCaseSensitive) = True) Then
        ; Get the text body of this MIME part.
Local $sTextBody = $oEmail.GetNthTextPartOfType($i,$searchSpec,$bInlineOnly,$bExcludeAttachments)
        ConsoleWrite("Got text body for " & $oSbContentType.GetAsString() & @CRLF)
    Else
        If ($oSbContentType.ContentsEqual("message/rfc822",$bCaseSensitive) = True) 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...
            $oAttachedEmail = ObjCreate("Chilkat.Email")
            $oBdMime = ObjCreate("Chilkat.BinData")
            $oEmail.GetNthBinaryPartOfTypeBd($i,$searchSpec,$bInlineOnly,$bExcludeAttachments,$oBdMime)
            $oAttachedEmail.SetFromMimeBd($oBdMime)
            ; Now your app can recursively process the attachedEmail...
        Else
            ; Get the bytes of this MIME body part.
            $oBd = ObjCreate("Chilkat.BinData")
            $oEmail.GetNthBinaryPartOfTypeBd($i,$searchSpec,$bInlineOnly,$bExcludeAttachments,$oBd)
            ConsoleWrite("Got binary body for " & $oSbContentType.GetAsString() & " numBytes = " & $oBd.NumBytes & @CRLF)
        EndIf

    EndIf

    $oSbContentType.Clear 
    $i = $i + 1
Wend