C
C
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 C Downloads
#include <C_CkEmail.h>
#include <C_CkStringBuilder.h>
#include <C_CkBinData.h>
void ChilkatSample(void)
{
BOOL success;
HCkEmail email;
HCkStringBuilder sbContentType;
BOOL caseSensitive;
BOOL inlineOnly;
BOOL excludeAttachments;
const char *searchSpec;
int numParts;
int i;
const char *textBody;
HCkEmail attachedEmail;
HCkBinData bdMime;
HCkBinData bd;
success = 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
email = CkEmail_Create();
success = CkEmail_LoadEml(email,"qa_data/eml/sample.eml");
if (success == FALSE) {
printf("Failed to load .eml\n");
CkEmail_Dispose(email);
return;
}
sbContentType = CkStringBuilder_Create();
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)
inlineOnly = FALSE;
excludeAttachments = FALSE;
searchSpec = "*/*";
numParts = CkEmail_GetNumPartsOfType(email,searchSpec,inlineOnly,excludeAttachments);
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) == TRUE) {
// Get the text body of this MIME part.
textBody = CkEmail_getNthTextPartOfType(email,i,searchSpec,inlineOnly,excludeAttachments);
printf("Got text body for %s\n",CkStringBuilder_getAsString(sbContentType));
}
else {
if (CkStringBuilder_ContentsEqual(sbContentType,"message/rfc822",caseSensitive) == TRUE) {
// 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...
attachedEmail = CkEmail_Create();
bdMime = CkBinData_Create();
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.
bd = CkBinData_Create();
CkEmail_GetNthBinaryPartOfTypeBd(email,i,searchSpec,inlineOnly,excludeAttachments,bd);
printf("Got binary body for %s numBytes = %d\n",CkStringBuilder_getAsString(sbContentType),CkBinData_getNumBytes(bd));
}
}
CkStringBuilder_Clear(sbContentType);
i = i + 1;
}
CkEmail_Dispose(email);
CkStringBuilder_Dispose(sbContentType);
CkEmail_Dispose(attachedEmail);
CkBinData_Dispose(bdMime);
CkBinData_Dispose(bd);
}