使用 LumiSoft.Net.POP3.Client 接收邮件

来源:互联网 发布:土豆视频mac版下载 编辑:程序博客网 时间:2024/05/21 12:48
.Net FCL 里自带了SMTP的实现System.Net.Mail,但是没有POP3的实现,要想使用.Net通过代码接收邮件,就只能通过第三方的组件了。这里我给大家介绍一下我常用的LumiSoft.Net.POP3.Client。

LumiSoft.Net是由Ivar Lumi开发的免费,开放源码的.Net网络协议库,包含了DNS Client, FTP Client/Server, ICMP, IMAP Client/Server, MIME, NNTP, POP3 Client/Server, SMTP Client/Server等协议/规范的实现。你可以在这里下载所有的源码/二进制文件/文档,也可以在LumiSoft.Net Forum里获取支持。

我们要做的首先当然是下载LumiSoft.Net类库,并下载LumiSoft.Net文档,然后在自己的项目里引用LumiSoft.Net了.

接收邮件的代码如下,需要说明的是邮件的内容是经过MIME格式的,所以需要使用Mime.Parse()进行处理。
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->using System;
using LumiSoft.Net.POP3.Client;
using LumiSoft.Net.Mime;

   
public List<Mime> GetEmails()
    {
       
//需要首先设置这些信息
        string pop3Server;
       
int pop3Port;
       
bool pop3UseSsl;
       
string username, password;
        List
<string> gotEmailIds;
       
        List
<Mime> result=new List<Mime>();
       
using(POP3_Client pop3= new POP3_Client())
        {
           
//与Pop3服务器建立连接
            pop3.Connect(pop3Server, pop3Port, pop3UseSsl);
           
//验证身份
            pop3.Authenticate(username, password,false);
           
           
//获取邮件信息列表
            POP3_MessagesInfo infos = pop3.GetMessagesInfo();
           
           
foreach (POP3_MessageInfo infoin infos)
            {
               
//每封Email会有一个在Pop3服务器范围内唯一的Id,检查这个Id是否存在就可以知道以前有没有接收过这封邮件
                if(gotEmailIds.Contains(info.MessageUID))
                   
continue;

               
//获取这封邮件的内容
                byte[] bytes= pop3.GetMessage(info);
               
//记录这封邮件的Id
                gotEmailIds.Add(info.MessageUId);

               
//解析从Pop3服务器发送过来的邮件信息
                Mime mime=Mime.Parse(bytes);
               
                result.Add(mime);
            }
        }
       
return result;
    }


关于如何使用MIME这个类,大家可以看文档。这里提供一个简单的示例。
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->    publicvoid ShowEmail(Mime m)
    {
        Console.WriteLine(
"From: {0}", m.MainEntity.From.ToAddressListString());
       
        Console.WriteLine(
"To: {0}", m.MainEntity.To.ToAddressListString());
       
        Console.WrtieLine(
"Time: {0}", m.MainEntity.Date);
       
        Console.WriteLine(
"Subject: {0}", m.MainEntity.Subject);
       
        Console.WriteLine(
"Plain Body: {0}", m.BodyText);
       
        Console.WriteLine(
"Html Body: {0}", m.BodyHtml);
    }