簡體   English   中英

僅獲取 MIME 電子郵件的“文本/純文本”位

[英]Get just the 'text/plain' bit of a MIME email

我正在為我正在處理的項目解析電子郵件。 到目前為止,我連接到一個 pop3 郵件服務器,下載那里的所有郵件並通過它循環獲取發件人、主題和正文。

然后我解碼 base64 正文,這給我留下了一個多部分 MIME 消息,就像我自己發送的以下測試電子郵件......

多部分 MIME 電子郵件

我需要能夠拆分此 Multipart MIME 電子郵件正文,以便我可以擁有一個僅包含郵件純文本版本的字符串和另一個包含 html 部分的字符串。

我對郵件可能有的其他任何東西都不感興趣……附件之類的東西都可能被丟棄。

任何人都可以指出我正確的方向嗎?

如果我打算使用 3rd 方控件,有沒有人知道任何能夠做到這一點的免費軟件? 我永遠不需要編碼,只需解碼。

假設您在電子郵件中有已提取的標題,以便您可以獲得用於識別電子郵件中部分邊界的字符串,您可以使用如下代碼進行解析:

Imports System.IO
Imports System.Text.RegularExpressions

Module Module1

    Sub Main()
        Dim sampleEmail = File.ReadAllText("C:\temp\SampleEmail.eml")
        Dim getBoundary As New Regex("boundary=(.*?)\r\n")
        Dim possibleBoundary = getBoundary.Matches(sampleEmail)
        Dim boundary = ""
        If possibleBoundary.Count = 0 Then
            Console.WriteLine("Could not find boundary specifier.")
            End
        End If

        ' the boundary string may or may not be surrounded by double-quotes
        boundary = possibleBoundary(0).Groups(1).Value.Trim(CChar(""""))

        Console.WriteLine(boundary)

        boundary = vbCrLf & "--" & boundary
        Dim parts = Regex.Split(sampleEmail, Regex.Escape(boundary))

        Console.WriteLine("Number of parts: " & parts.Count.ToString())

        ' save the parts to one text file for inspection
        Using sw As New StreamWriter("C:\temp\EmailParts.txt")
            For i = 0 To parts.Count - 1
                ' this is where you would find the part with "Content-Type: text/plain;" -
                ' you may also need to look at the charset, e.g. charset="utf-8"
                sw.WriteLine("PART " & i.ToString())
                sw.WriteLine(parts(i))
            Next
        End Using

        Console.ReadLine()

    End Sub

End Module

我用來測試的電子郵件沒有涉及任何 base-64 編碼。

我建議使用我的免費/開源MimeKit庫來完成此任務,而不是使用正則表達式解決方案。

我不太了解 VB.NET,所以下面的代碼片段可能不太正確(我是 C# 人),但它應該讓你大致了解如何完成你想要的任務:

Dim message = MimeMessage.Load ("C:\email.msg");
Dim html = message.HtmlBody;
Dim text = message.TextBody;

如您所見,MimeKit 使這種事情變得非常簡單。

A = E1 = 80 =

= B8 = E1 = 80 = 80 = E1 = 80 = BC = E1 = 80-8A = E1 = 80 = BA; = 50 = 61 = 74 = 69 = 65 = 6E = 74;;

-可打印:= 50 = 61 = 74 = 69 = 65-6 E = 74 = 20 = E1 = 80 = 99 = E1 = 80 = 81 = E1 = 80 = 84 = E1 = 80 = BA =

E1 = 81 = 80 =

= E1 = 80 = 84 = E1 = 80 = BA = E1 = 80 = B8 = E1 = 80 = 80 = E1 = 80 = BC = E1 = 80 = 8A = E1 = 80 = BA

B = E1 = 80 = AD = E1 = 80 = AF; = 50 = 61 = 74 = 69 = 65 =

6E = 74;;

E1 = 80 = AF =

結束: VCARD

暫無
暫無

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

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