Search code examples
htmlemailmime-typesmailkitmimekit

Mailkit TextPart IsHtml Content type check does not work


Dear Friends,

 TextPart textPart = new TextPart();
    textPart.Text = body; // body contains the html text.
    if(textPart.IsHtml)
    {
    }else { }

text part IsHtml is not giving me the correct result. I know my body text contains HTML but still, it goes in else condition.

Then I look into this conversation but when I wrote it. It gives error on ContentType. char does not contain the information of contentType.

 var bodyii = textPart.Text.FirstOrDefault(x => x.ContentType.IsMimeType("text", "html"));

Can anyone point out what I am doing wrong?


Solution

  • textPart.IsHtml doesn't examine the textPart.Text to see if it contains html tags, it examines the textPart.ContentType to see if it matches text/html. When you create a TextPart using the default constructor, it creates text/plain, not text/html.

    You need to use:

    TextPart textPart = new TextPart ("html");
    

    The following code of yours:

    var bodyii = textPart.Text.FirstOrDefault(x => x.ContentType.IsMimeType("text", "html"));
    

    gets an error because textPart.Text is a string, which means your LINQ expression operates on char elements and a char does not have a ContentType property.

    In other words, if you do:

    textPart.Text = "This is some text.";
    

    Then your LINQ expression, translated to more simplistic C# code using a forewach loop would look like this:

    char bodyii = 0;
    foreach (char x in textPart.Text)
    {
        if (x.ContentType.IsMimeType("text", "html"))
        {
            bodyii = x;
            break;
        }
    }
    

    Does that code make sense to you? It shouldn't which is why the compiler is giving you an error.