Retrieving AlternateView's of email

放肆的年华 提交于 2019-12-05 06:41:37

Its not immediately possible to parse an email with the classes available in the System.Net.Mail namespace; you either need to create your own MIME parser, or use a third party library instead.

This great Codeproject article by Peter Huber SG, entitled 'POP3 Email Client with full MIME Support (.NET 2.0)' will give you an understanding of how MIME processing can be implemented, and the related RFC specification articles.

You can use the Codeproject article as a start for writing your own parser, or appraise a library like SharpMimeTools, which is an open source library for parsing and decoding MIME emails.

http://anmar.eu.org/projects/sharpmimetools/

Hope this helps!

John Kaster

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));

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));
    }

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!