大家都知道,SMTP/POP3是基于文本型的交互协议,由于整个协议解析过程比较冗长,牵涉到socket编程以及字符处理两个大块内容,因此一般情况下不太愿意在一个项目里面自己来做这块,所谓轮子不用自己造,还是拿来主义实在,毕竟是项目开发而不是产品开发,效率是至关重要的,分析一下如下C#的3个著名的开源平台:
http://sourceforge.net/
我们发现http://hpop.sourceforge.net/有个不错的开源组件可供我们采用,因此才有如下的快速实现代码。
static void Main(string[] args)
{
string userName = "xxxx";
string userPassword = "xxxx";
string pop3HostName = "xxxxx";
using (Pop3Client client = new Pop3Client())
{
// Connect to the server
client.Connect(pop3HostName, 110, false);
// Authenticate ourselves towards the server
client.Authenticate(userName, userPassword);
// Get the number of messages in the inbox
int messageCount = client.GetMessageCount();
// We want to download all messages
List<Message> allMessages = new List<Message>(messageCount);
// Messages are numbered in the interval: [1, messageCount]
// Attension: message numbers are 1-based.
for (int i = 1; i <= messageCount; i++)
{
Message message = client.GetMessage(i);
List<MessagePart> attachments = message.FindAllAttachments();
Console.WriteLine(String.Format("Message\attachment:{0}|{0}", i, attachments.Count));
foreach (MessagePart attachment in attachments)
{
FileInfo fi = new FileInfo(@"d:\share\" + attachment.FileName);
attachment.Save(fi);
}
}
// disconnect and release resource occupation.
client.Disconnect();
}
}
别忘了添加如下的引用部分:
using System.IO;
using OpenPop.Common;
using OpenPop.Mime;
using OpenPop.Pop3;
整个实现过程不过才短短15分钟,还是拿来主义效率高啊。