Lua Requires Chilkat v9.5.0.95+
Lua
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.Chilkat Lua Downloads
local chilkat = require("chilkat")
-- 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
local email = chilkat.Email.new()
local success = email:load_eml("qa_data/eml/sample.eml")
if not success then
print("Failed to load .eml")
return
end
local sbContentType = chilkat.StringBuilder.new()
local caseSensitive = 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 inlineOnly = false
local excludeAttachments = false
local searchSpec = "*/*"
local numParts = email:get_num_parts_of_type(searchSpec, inlineOnly, excludeAttachments)
local i = 0
while i < numParts do
-- What is the Content-Type of this MIME part?
sbContentType:append(email:get_nth_content_type(i, searchSpec, inlineOnly, excludeAttachments))
if sbContentType:starts_with("text/", caseSensitive) then
-- Get the text body of this MIME part.
local textBody = email:get_nth_text_part_of_type(i, searchSpec, inlineOnly, excludeAttachments)
print("Got text body for " .. sbContentType:get_as_string())
elseif sbContentType:contents_equal("message/rfc822", caseSensitive) 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...
local attachedEmail = chilkat.Email.new()
local bdMime = chilkat.BinData.new()
email:get_nth_binary_part_of_type_bd(i, searchSpec, inlineOnly, excludeAttachments, bdMime)
attachedEmail:set_from_mime_bd(bdMime)
-- Now your app can recursively process the attachedEmail...
else
-- Get the bytes of this MIME body part.
local bd = chilkat.BinData.new()
email:get_nth_binary_part_of_type_bd(i, searchSpec, inlineOnly, excludeAttachments, bd)
print("Got binary body for " .. sbContentType:get_as_string() .. " numBytes = " .. bd.num_bytes)
end
sbContentType:clear()
i = i + 1
end