Discuss this help topic in SecureBlackbox Forum

MIME: Get message text

First of all, it's needed to find an appropriate text part. There can be several text parts in one message. Also, an attachment can also have its Content-Type field set to "text". So it is necessary to find a part, whose IsText() method returns true, and whose IsAttachment() method returns “false”. If your program can handle only a certain text type (for example, only plain text), you need to check the part's ContentSubtype property too.

The following method returns the first found text part. If a subtype is specified, the method checks it as well. If no such part found in the message, the method returns null.

C#:


TElMessagePart FindTextPart(TElMessagePart part, string subtype = null)
{
    if (part != null && !part.IsAttachment() && part.IsText())
        if (String.IsNullOrEmpty(subtype) ||
            String.Equals(part.ContentSubtype, subtype, StringComparison.InvariantCultureIgnoreCase))
                return part;

    for (int i = 0; i < part.PartsCount; i++)
    {
        TElMessagePart child = FindTextPart(part.GetPart(i), subtype);
        if (child != null)
            return child;
    }

    return null;
}

...
TElMessagePart textPart = FindTextPart(message.MainPart, "html");
if (textPart != null)
{
    string text = null;
    int err = textPart.GetText(ref text);
    if (err != 0)
        Console.WriteLine("There were issues while getting the part text: {0}", err);
    else
        Console.WriteLine(text);
}

How To articles about MIME

Discuss this help topic in SecureBlackbox Forum