簡體   English   中英

用c#解析郵件正文

[英]Parsing email body with c#

我有一個名為email_archive的電子郵件數據庫表。 該表包含一個名為body的字段和另一個名為raw_headers的字段。 我想使用C#(在SharePoint webpart中)在屏幕上顯示此表的內容。 我一直在嘗試找到一個可以解析主體的庫,這樣我就可以將消息的各個部分返回到窗口。 我嘗試過Limilabs的庫,並下載了其他幾個庫。 但是,所有這些似乎都需要一個EML格式的電子郵件。

最新的嘗試是嘗試使用MailUtilies

MimeMessage mm = new MimeMessage(header + message);

但這是失敗的,因為看起來格式沒有通過MimeMessage完整性檢查。

有沒有人知道使用原始標題和正文內容將電子郵件解析為其組成部分的方法。

標題看起來像這樣

MIME-Version: 1.0
Received: from server.domain.com (10.20.205.104) by
 mail.domain.com (xx.xx.xx.xx) with Microsoft SMTP Server id
 8.1.436.0; Mon, 16 Sep 2013 14:33:54 -0700
Received: from server (localhost.localdomain [127.0.0.1])   by
 server.domain.com (8.13.8/8.13.8) with ESMTP id r8GLX4vm007046 for
 <myaddress@domain.com>; Mon, 16 Sep 2013 14:33:04 -0700
From: "service@domain.com" <service@domain.com>
To: My Name <myaddress@domain.com>
Date: Mon, 16 Sep 2013 14:33:04 -0700
Subject: Some Topic
Thread-Topic: Some Topic
Thread-Index: Ac6zJHFgOvb7ZAdeTJC8DzqnAvdnOw==
Message-ID: <153372.442207427-sendEmail@gserver>
Reply-To: "service@domain.com" <service@domain.com>
Accept-Language: en-US
Content-Language: en-US
X-MS-Exchange-Organization-AuthAs: Internal
X-MS-Exchange-Organization-AuthMechanism: 10
X-MS-Exchange-Organization-AuthSource: mail.domain.com
X-MS-Has-Attach:
X-MS-TNEF-Correlator:
Content-Type: multipart/alternative;
    boundary="_000_153372442207427sendEmailgroundwork_"

消息看起來像這樣

--_000_153372442207427sendEmailgroundwork_
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

Some message to dispaly

--_000_153372442207427sendEmailgroundwork_
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable

<html><head><style type=3D'text/css'> p,h1 { font-family: arial; } 
</style></head><body>
 <p>Some message to display</p>
 </body></html>


--_000_153372442207427sendEmailgroundwork_--

我通過使用OpenPop.Net的庫找到了答案。

public void addMessage(string message, string header) {
  string full_body = header + "\n" + message;
  System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
  Byte[] full_body_bytes = encoding.GetBytes(full_body);
  Message mm = new Message(full_body_bytes);

  //do stuff here.
}

我剛剛使用了MimeKit ,它非常適合解析附件。 它看起來功能齊全,跨平台。

如果你有標題和正文,那么重新創建整個eml是微不足道的:

string eml = header + "\r\n\r\n" + body;  

MIME格式的標題和正文用一個空行分隔。 另一個答案使用'\\ n' - 這是不正確的,因為MIME要求“\\ r \\ n”序列作為行結尾。

如果您的標題字符串已經以新行結束,則只需添加一個新行(“\\ r \\ n”)。

您需要將標題和正文與\\r\\n\\r\\n分隔符合並。 以下代碼演示了:

string msgContent = header.TrimEnd("\r\n") + "\r\n\r\n" + message;
byte[] bytes = Encoding.ASCII.GetBytes(msgContent);
ComponentPro.Net.Mail.MailMessage msg = new ComponentPro.Net.Mail.MailMessage(bytes);

//
// Access your parsed message here
//

該代碼使用Ultimate Mail庫

暫無
暫無

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

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