制作一个ASP.NET MVC4论坛项目,该项目需要将以往十多年的Mail List(邮件列表)内容都导入到新的论坛中,因此需要能够将邮件的标题、发布时间、发布人及邮件内容导入到论坛的数据库内。.Net并没有提供内置的读取POP3邮件内容的类库,因此,只有在网上查询可用的类库。
查询的结果,OpenPop.dll(官网下载地址:http://sourceforge.net/projects/hpop/)是符合要求的一种。
下面的代码只给出了最核心、最简捷的内容,以Console方式完成。 利用Pop3Client对象的Connect方法,给出PoP3 Server、端口号、是否需要SSL连接;Authenticate方法则给出POP3的账号及密码。
在使用中,标题、发送人及发送时间及许多其它信息(如cc bcc to等等)都可以使用简单的方法取出(如下面代码所示),因为它们都是以plaintext的方式发送的,但对于邮件内容(body)和附件(attachment),由于涉及到multipart格式,因此,为能简单地取出。在下面的代码中,对于邮件内容的提取方式,最主要的是两种:一种是text格式,另外一种是multipart格式,这两种格式的提取办法是不同的。
下面的代码由笔者实际调试,真实可用。
using System;
using OpenPop.Pop3;
using OpenPop.Mime;
using System.Collections.Generic; #region using OpenPop.dll to read email
public static void ReadPop3()
{
using (Pop3Client client = new Pop3Client())
{
if (client.Connected)
{
client.Disconnect();
} // Connect to the server, false means don't use ssl
client.Connect("pop3.263.net", , false); // Authenticate ourselves towards the server by email account and password
client.Authenticate("wusir@263.net", ""); //email count
int messageCount = client.GetMessageCount(); //i = 1 is the first email; 1 is the oldest email
for (int i = ; i <= messageCount; i++)
{
Message message = client.GetMessage(i); string sender = message.Headers.From.DisplayName;
string from = message.Headers.From.Address;
string subject = message.Headers.Subject;
DateTime Datesent = message.Headers.DateSent; MessagePart messagePart = message.MessagePart; //email body,
string body = " ";
if (messagePart.IsText)
{
body = messagePart.GetBodyAsText();
}
else if (messagePart.IsMultiPart)
{
MessagePart plainTextPart = message.FindFirstPlainTextVersion();
if (plainTextPart != null)
{
// The message had a text/plain version - show that one
body = plainTextPart.GetBodyAsText();
}
else
{
// Try to find a body to show in some of the other text versions
List<MessagePart> textVersions = message.FindAllTextVersions();
if (textVersions.Count >= )
body = textVersions[].GetBodyAsText();
else
body = "<<OpenPop>> Cannot find a text version body in this message.";
}
} }
}
}
#endregion
更多帮助内容,可以参见官网帮助文档:http://hpop.sourceforge.net/documentation/index.html
另外,如果直接读取Outlook(OE)或者Windows Live Mail格式的邮件内容(扩展名.eml),可以使用LumiSoft.Net.dll完成