Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving AlternateView's of email

I can't seem to retrieve the AlternateView from System.Net.Mail.AlternateView.

I have an application that is pulling email via POP3. I understand how to create an alternate view for sending, but how does one select the alternate view when looking at the email. I've have the received email as a System.Net.MailMessage object so I can easily pull out the body, encoding, subject line, etc. I can see the AlternateViews, that is, I can see that the count is 2 but want to extract something other than the HTML that is currently returned when I request the body.

Hope this makes some amount of sense and that someone can shed some light on this. In the end, I'm looking to pull the plaintext out, instead of the HTML and would rather not parse it myself.

like image 571
Douglas Anderson Avatar asked Nov 14 '08 22:11

Douglas Anderson


3 Answers

Mightytighty is leading you down the right path, but you shouldn't presume the type of encoding. This should do the trick:

var dataStream = view.ContentStream;
dataStream.Position = 0;
byte[] byteBuffer = new byte[dataStream.Length];
var encoding = Encoding.GetEncoding(view.ContentType.CharSet);
string body = encoding.GetString(byteBuffer, 0, 
    dataStream.Read(byteBuffer, 0, byteBuffer.Length));
like image 190
John Kaster Avatar answered Sep 28 '22 17:09

John Kaster


I was having the same problem, but you just need to read it from the stream. Here's an example:

    public string ExtractAlternateView()
    {
        var message = new System.Net.Mail.MailMessage();
        message.Body = "This is the TEXT version";

        //Add textBody as an AlternateView
        message.AlternateViews.Add(
            System.Net.Mail.AlternateView.CreateAlternateViewFromString(
                "This is the HTML version",
                new System.Net.Mime.ContentType("text/html")
            )
        );

        var dataStream = message.AlternateViews[0].ContentStream;
        byte[] byteBuffer = new byte[dataStream.Length];
        return System.Text.Encoding.ASCII.GetString(byteBuffer, 0, dataStream.Read(byteBuffer, 0, byteBuffer.Length));
    }
like image 38
mightytightywty Avatar answered Sep 28 '22 16:09

mightytightywty


There is a simpler way:

public string GetPlainTextBodyFromMsg(MailMessage msg)
{
    StreamReader plain_text_body_reader = new StreamReader(msg.AlternateViews[0].ContentStream);
    return(plain_text_body_reader.ReadToEnd());
}

This works if the first alternative view is the plain text version, as it happens usually.

like image 26
carlos357 Avatar answered Sep 28 '22 15:09

carlos357