MIME Component Recursive Decoding for Nested Messages


MIME messages may contain nested structures where a part includes another encoded MIME entity, requiring traversal of all parts to decode embedded content.

Recursive MIME Decoding Example

A recursive function can be used to decode each entity and process its parts, including sub-MIME messages, text content, and attachments.

//C#
private void MimeDecode(string EntityHeaders, string Entity)
{
  Mime mime1 = new Mime();
  mime1.MessageHeadersString = EntityHeaders;
  mime1.Message = Entity;
  mime1.DecodeFromString();
  for (int i = 0; i <= mime1.Parts.Count - 1; i++)
  {
    // If the Content-Type is "Multipart/????", then that part is an encoded entity
    if (mime1.Parts[i].ContentType.ToLower().StartsWith("multipart"))
    {
      MimeDecode(mime1.Parts[i].Headers, mime1.Parts[i].DecodedString);
    }
    // If the part is plain text
    if (mime1.Parts[i].Filename == "" && 
        mime1.Parts[i].ContentType.ToString() == "text/plain")
    {
      // At this point we could check the ContentTypeAttr field for the charset
      // and use the charset (if set) when displaying the text.
      // For simplicity we will skip checking the charset in this example.
      Console.WriteLine("Plain text: " + mime1.Parts[i].DecodedString);
    }
    // If the part has an associated Filename, it is an attachment
    if (!mime1.Parts[i].Filename.Equals(""))
    {
      Console.WriteLine("Attachment: " + mime1.Parts[i].Filename);
    }
  }
}
//VB6
Private Function MimeDecode(EntityHeaders As String, Entity As String)
Dim mime1 As New MIME
Dim i As Integer
mime1.MessageHeadersString = EntityHeaders
mime1.Message = Entity
mime1.DecodeFromString
For i = 0 To mime1.PartCount - 1
    If (InStr(LCase(mime1.PartContentType(i)), "multipart") > 0) Then
        MimeDecode mime1.PartHeaders(i), mime1.PartDecodedString(i)
    ElseIf (mime1.PartFilename(i) = "" And mime1.PartContentType(i) = "text/plain") Then
        Debug.Print "Plain text: " & mime1.PartDecodedString(i)
    ElseIf (mime1.PartFilename(i) <> "") Then
        Debug.Print "Attachment: " & mime1.PartFilename(i)
    End If
Next i
End Function

This approach can be extended to handle additional content types and conditions, enabling flexible processing of complex MIME structures.

Note: These examples use the IPWorks Version 8 API and may require minor adjustments for earlier versions.

We appreciate your feedback. If you have any questions, comments, or suggestions about this article please contact our support team at support@nsoftware.com.