Discuss this help topic in SecureBlackbox Forum

MIME: Load and parse message

E-mail messages contain one or more message parts organized into a hierarchical structure. Generally, there can be unlimited levels in that hierarchy.

Message parts are divided into 2 major types: multipart parts and simple parts. Multipart parts don't contain any data, but they contain only other message parts (including other multipart parts). Simple parts cannot contain other parts but contain the data of certain type as specified in their Content-Type header field.

Usually, it's needed to get the message text and extract the attached data. To do this it's needed to iterate through the message parts and find text parts (Content-Type header field of such parts is set to "text") and attachment parts (Content-Disposition header field of such parts is set to "attachment").

The following code snippet shows the entire message structure:

C#:


void PrintMessageStructure(string fileName)
{
    FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
    try
    {
        TElMessage message = new TElMessage(false, "");
        int err = message.ParseMessage(stream, "", "", SBMIME.__Global.mpoLoadData, false, false, false);

        if (err != 0)
        {
            Console.WriteLine("Message parsing error: {0}", err);
            return;
        }

        PrintPartStructure(message.MainPart, 0);
    }
    finally
    {
        stream.Close();
    }
}

void PrintPartStructure(TElMessagePart part, int level)
{
    string indent = new String(' ', level * 2);

	// this line prints information about the part
    Console.WriteLine("{0}[{1}] {2}/{3} {4}", indent, level, part.ContentType, part.ContentSubtype, (part.IsAttachment()) ? "(attachment)" : "");

	// if there are "child parts" in this part, print them as well
    for (int i = 0; i < part.PartsCount; i++)
        PrintPartStructure(part.GetPart(i), level + 1);
}

This code shows the following structure for the message created in the article about creation of the complex message:

[0] multipart/mixed
  [1] multipart/alternative
    [2] text/plain
    [2] multipart/related
      [3] text/html
      [3] image/jpeg
  [1] application/octet-stream (attachment)

How To articles about MIME

Discuss this help topic in SecureBlackbox Forum