MIME Code Example: Recursive decoding

Many times, a MIME message that you obtain will be nested. That the MIME message consists of multiple parts, and one of those parts may itself be another entire MIME entity. In order to effectively handle these types of message you can create a function to recursively decode the message. For example:

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 can of course be expanded to check for other ContentTypes or conditions. This should provide you with a basic idea of how to approach decoding nested MIME entities recursively.

Note: The above code examples use the API of IPWorks Version 8. This code will need to be modified slightly if you are using an older version of IPWorks

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