簡體   English   中英

檢索AlternateView的電子郵件

[英]Retrieving AlternateView's of email

我似乎無法從System.Net.Mail.AlternateView檢索AlternateView。

我有一個通過POP3拉電子郵件的應用程序。 我了解如何創建備用視圖以進行發送,但在查看電子郵件時如何選擇備用視圖。 我收到的電子郵件是一個System.Net.MailMessage對象,所以我可以輕松地拉出正文,編碼,主題行等。我可以看到AlternateViews,也就是說,我可以看到計數是2但是想要在我請求正文時,提取當前返回的HTML以外的內容。

希望這有一點意義,有人可以對此有所了解。 最后,我希望將明文拉出來,而不是HTML,而不是自己解析它。

Mightytighty正引領你走上正確的道路,但你不應該假設編碼的類型。 這應該做的伎倆:

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

我遇到了同樣的問題,但你只需要從流中讀取它。 這是一個例子:

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

有一種更簡單的方法:

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

如果第一個替代視圖是純文本版本,則通常會發生這種情況。

無法立即解析具有System.Net.Mail命名空間中可用類的電子郵件; 您需要創建自己的MIME解析器,或使用第三方庫。

Peter Huber SG撰寫的題為“具有完整MIME支持的POP3電子郵件客戶端(.NET 2.0)”的偉大Codeproject文章將幫助您了解如何實現MIME處理以及相關的RFC規范文章。

您可以使用Codeproject文章作為編寫自己的解析器的開始,或者評估像SharpMimeTools這樣的庫,它是一個用於解析和解碼MIME電子郵件的開源庫。

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

希望這可以幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM