首页 > 开发 > 综合 > 正文

c#封装jmail的pop3收邮件

2024-07-21 02:30:05
字体:
来源:转载
供稿:网友

*
w3 jmail v4.4 professional 的获取请自行 google!
或参阅 http://community.csdn.net/expert/topicview.asp?id=3739405
w3 jmail v4.4 professional 是一个 com 的组件,我用 c# 把其 pop3 com 类封装成
一个用于收取邮件的 .net 组件:
实现了
 //同步事件
  public event messageseventhandler messagereceived; //一封邮件已收到本地
  public event messageseventhandler messagereceive; //一封邮件正到达
  //可用于收取邮件的每个附件处理
  public event attachmentseventhandler attachmentreceive; //一封邮件的附件正到达

 //发生异常事件
  public event messageseventhandler messageexception;
  public event attachmentseventhandler attachmentexception;

因此在调用该组件的主调程序中可根据分析邮件的主题或附件等结果作不同处理!

将如下所有代码:
1.复制到 microsoft visual studio .net 2003 的新建的 "控制台应用程序" 项目的 *.cs 文件中
2.然后添加引用 jmail 4.x library!
jmail 的注册方法,运行命令行: regsvr32 e:/jmail/jmail.dll
3.f5 运行

或者
将如下所有代码:
1.复制到任意一个 *.cs 文件中保存!(如: e:/temp/njmail.cs)
2.使用 tlbimp.exe(类型库导入程序)实用工具生成一个 .net 程序集
执行命令行: (位于 ms vs.net 安装目录下的: e:/msvs.net/sdk/v1.1/bin/tlbimp.exe)
tlbimp.exe e:/jmail/jmail.dll /out:e:/temp/jmail.net.dll /namespace:jmail
生成的 jmail.net.dll 与 *.cs 文件放在同一目录下!
3.执行 csc 命令行编译 *.cs
编译成 exe : (这里是为了演示测试效果所以编译成 exe)
csc.exe njmail.cs /r:jmail.net.dll
编译成 dll ,即可由别的 .net 程序添加引用:
csc.exe /t:library njmail.cs /r:jmail.net.dll

(当然也可将 namespace microshaoft.njmail 下的代码单独编译成 dll)
*/

namespace microshaoft.njmail
{
 //using jmail;
 //using system;

 public class pop3
 {
  public delegate void messageseventhandler(messagesstate omessagesstate);
  public delegate void attachmentseventhandler(attachmentsstate oattachmentsstate);

  //异步事件
  public event messageseventhandler messagesreceiveasync;
  public event attachmentseventhandler attachmentsreceiveasync;

  //同步事件
  public event messageseventhandler messagereceived;
  public event messageseventhandler messagereceive;
  public event attachmentseventhandler attachmentreceive;

  //发生异常事件
  public event messageseventhandler messageexception;
  public event attachmentseventhandler attachmentexception;

  private string _username;
  private string _password;
  private string _server;
  private int _port = 110;

  private static object _lockobject = new object();

  public pop3(string username,string password,string server,int port)
  {
   this._username = username;
   this._password = password;
   this._server = server;
   this._port = port;
  }

  public pop3(string username,string password,string server)
  {
   this._username = username;
   this._password = password;
   this._server = server;
  }

  //[mtathread]
  public void execute()
  {
   this.execute(false);
  }

  public void execute(bool isasync)
  {
   jmail.pop3class pop3 = new jmail.pop3class();
   try
   {
    pop3.timeout = 0;
    pop3.connect(this._username,this._password,this._server,this._port);
    jmail.messagesclass jms = (jmail.messagesclass) pop3.messages;
    int i = jms.count;
    messagesstate omss = null;
    for (int i = 0; i < i - 1; i++)
    {
     try
     {
      jmail.messageclass jmc = (jmail.messageclass) jms[i+1];
      if (omss == null)
      {
       omss = new messagesstate(i+1,jmc,jms,pop3);
       if (this.messagereceive != null)
       {
        this.messagereceive(omss);
       }
      }
      if (!omss.cancelcurrent)
      {
       if (isasync)
       {
        //system.iasyncresult iar =
        (new messageseventhandler(this.messageexecuteasync)).begininvoke(omss,new system.asynccallback(this.onmessagecallback),omss);
       }
       else
       {
        int j = jmc.attachments.count;
        attachmentsstate oass = null;
        for (int j = 0; j < j; j++)
        {
         try
         {
          if (oass == null)
          {
           oass = new attachmentsstate(j,omss);
           if (this.attachmentreceive != null)
           {
            this.attachmentreceive(oass);
           }
          }
          if (!oass.cancelcurrent)
          {
           string s = oass.filename;
           omss.setfilepath(system.io.path.getdirectoryname(s) + @"/");
           oass.savetofile(s);
          }
         }
         catch (system.exception e)
         {
          if (this.attachmentexception != null)
          {
           oass.exception = e;
           this.attachmentexception(oass);
           if (oass.exceptionaction == microshaoft.njmail.exceptionactions.cancelall)
           {
            break;
           }
           else
           if (oass.exceptionaction == microshaoft.njmail.exceptionactions.retry)
           {
            j--;
           }
           else
           if (oass.exceptionaction == microshaoft.njmail.exceptionactions.ignore)
           {
            //continue;
           }
           else
           if (oass.exceptionaction == microshaoft.njmail.exceptionactions.throw)
           {
            throw e;
           }
          }
          else
          {
           throw e;
          }
         }
        }
        if (this.messagereceived != null)
        {
         this.messagereceived(omss);
        }
       }
      }
     }
     catch (system.exception e)
     {
      if (this.messageexception != null)
      {
       omss.exception = e;
       this.messageexception(omss);
       if (omss.exceptionaction == microshaoft.njmail.exceptionactions.cancelall)
       {
        break;
       }
       else
       if (omss.exceptionaction == microshaoft.njmail.exceptionactions.retry)
       {
        i--;
       }
       else
       if (omss.exceptionaction == microshaoft.njmail.exceptionactions.ignore)
       {
        //continue;
       }
       else
       if (omss.exceptionaction == microshaoft.njmail.exceptionactions.throw)
       {
        throw e;
       }
      }
      else
      {
       throw e;
      }
     }
    }
   }
   catch (system.exception e)
   {
    throw e;
   }
   finally
   {
    pop3.disconnect();
    pop3 = null;
   }
   //system.console.writeline("main end");
  }

  //[mtathread]
  private void messageexecuteasync(messagesstate omessagesstate)
  {
   int j = omessagesstate.jmessage.attachments.count;
   for (int j = 0; j < j; j++)
   {
    attachmentsstate oass = new attachmentsstate(j,omessagesstate);
    //system.iasyncresult iar =
    (new attachmentseventhandler(this.attachmentexecuteasync)).begininvoke(oass,new system.asynccallback(this.onattachemnetcallback),oass);
   }
  }

  //[mtathread]
  private void attachmentexecuteasync(attachmentsstate oattachmentsstate)
  {
   //
  }

  //[mtathread]
  private void onmessagecallback(system.iasyncresult iar)
  {
   messagesstate omss = (messagesstate) iar.asyncstate;
   if (this.messagesreceiveasync != null)
   {
    if (omss.jmessage.attachments.count == 0)
    {
     this.messagesreceiveasync(omss);
    }
   }
  }

  //[mtathread]
  private void onattachemnetcallback(system.iasyncresult iar)
  {
   attachmentsstate oass = (attachmentsstate) iar.asyncstate;
   if (this.attachmentsreceiveasync != null)
   {
    this.attachmentsreceiveasync(oass);
   }
   if (!oass.cancelcurrent)
   {
    try
    {
     oass.savetofile(oass.filename);
    }
    catch (system.exception e)
    {
     oass.exception = e;
     if (attachmentexception != null)
     {
      attachmentexception(oass);
      if (oass.exceptionaction == microshaoft.njmail.exceptionactions.cancelall)
      {

      }
      else
      if (oass.exceptionaction == microshaoft.njmail.exceptionactions.retry)
      {
       this.onattachemnetcallback((system.iasyncresult) oass);
      }
      else
      if (oass.exceptionaction == microshaoft.njmail.exceptionactions.ignore)
      {

      }
      else
      if (oass.exceptionaction == microshaoft.njmail.exceptionactions.throw)
      {
       throw e;
      }
     }
    }
   }
   if (this.messagesreceiveasync != null)
   {
    if (oass.attachmentscount == 0)
    {
     this.messagesreceiveasync(oass.messagesstate);
    }
   }
  }
 }

 public class messagesstate //messages 状态
 {
  private static object _lockobject = new object();
  private int _messageid;
  private jmail.messageclass _jmessage;
  private jmail.messagesclass _jmessages;
  private jmail.pop3class _jpop3;
  private string _filepath;
  private bool _cancelcurrent;

  private system.exception _exception;
  private exceptionactions _exceptionaction;

 

  public exceptionactions exceptionaction
  {
   get
   {
    return _exceptionaction;
   }
   set
   {
    this._exceptionaction = value;
   }
  }

  public system.exception exception
  {
   get
   {
    return _exception;
   }
   set
   {
    this._exception = value;
   }
  }

  public string filepath
  {
   get
   {
    return this._filepath;
   }
  }

  internal void setfilepath(string filepath)
  {
   this._filepath = filepath;
  }

  public bool cancelcurrent
  {
   get
   {
    return this._cancelcurrent;
   }
   set
   {
    this._cancelcurrent = value;
   }
  }

  public int messagescount //尚未处理的邮件数
  {
   get
   {
    //lock(messagesstate._lockobject)
    {
     return this._jmessages.count - this._messageid - 1;
    }
   }
  }

  public jmail.messagesclass jmessages
  {
   get
   {
    return this._jmessages;
   }
  }

  public jmail.messageclass jmessage
  {
   get
   {
    return this._jmessage;
   }
  }

  public int messageid
  {
   get
   {
    return this._messageid;
   }
  }

  internal messagesstate(int messageid,jmail.messageclass jmessage,jmail.messagesclass jmessages,jmail.pop3class jpop3)
  {
   this._messageid = messageid;
   this._jmessage = jmessage;
   this._jmessages = jmessages;
   this._jpop3 = jpop3;
  }

  public void deletesinglemessage()
  {
   lock(messagesstate._lockobject)
   {
    this.deletesinglemessage(this._messageid);
   }
  
  }

  public void deletesinglemessage(int messageid)
  {
   lock(messagesstate._lockobject)
   {
    this._jpop3.deletesinglemessage(messageid);
   }
  }

  public void deletemessages()
  {
   lock(messagesstate._lockobject)
   {
    this._jpop3.deletemessages();
   }
  }
 }


 public enum exceptionactions
 {
  cancelall,ignore,retry,throw
 }

 public class attachmentsstate //attachments 状态
 {
  private messagesstate _messagesstate;
  private int _attachmentid;
  private string _filename;
  private static object _lockobject = new object();
  private jmail.attachmentclass _jattachment;
  private bool _cancelcurrent;
  private system.exception _exception;
  private exceptionactions _exceptionaction;

  public exceptionactions exceptionaction
  {
   get
   {
    return _exceptionaction;
   }
   set
   {
    this._exceptionaction = value;
   }
  }

  public system.exception exception
  {
   get
   {
    return _exception;
   }
   set
   {
    this._exception = value;
   }
  }

  public bool cancelcurrent
  {
   get
   {
    return this._cancelcurrent;
   }
   set
   {
    this._cancelcurrent = value;
   }
  }

  public jmail.attachmentclass jattachment
  {
   get
   {
    return this._jattachment;
   }
  }

  public int attachmentscount //尚未处理的邮件附件数
  {
   get
   {
    //lock(attachmentsstate._lockobject)
    {
     return this._messagesstate.jmessage.attachments.count - this._attachmentid - 1;
    }
   }
  }

  public string filename
  {
   get
   {
    return this._filename;
   }
   set
   {
    this._filename = value;
   }
  }

  public messagesstate messagesstate
  {
   get
   {
    return this._messagesstate;
   }
  }

  public int attachmentid
  {
   get
   {
    return this._attachmentid;
   }
  }

  public void savetofile(string filename)
  {
   //if (!this.cancelcurrent)
   {
    this._jattachment.savetofile(filename);
   }
  }

  internal attachmentsstate(int attachmentid,messagesstate omessagesstate)
  {
   this._messagesstate = omessagesstate;
   this._attachmentid = attachmentid;
   this._jattachment = (jmail.attachmentclass) omessagesstate.jmessage.attachments[attachmentid];
   this._filename = system.string.format("[{0}].{1}.[{2}].{3}",omessagesstate.messageid,omessagesstate.jmessage.subject,attachmentid,this._jattachment.name);
  }
 }
}

//================================================================================================
//控制台测试程序:
namespace consoleapplicationtest
{
 using microshaoft.njmail;
 using pop = microshaoft.njmail.pop3;
 class apptest
 {
  pop pop1;
  bool isbusy = false;

  static void main()
  {

   //调用 windows 测试程序
   system.console.writeline("windowsapplicationtest begin:");
   windowsapplicationtest.form1.main0();
   system.console.writeline("windowsapplicationtest end.");

   system.console.writeline("consoleapplicationtest begin:");
   apptest a = new apptest();
   a.pop1 = new pop("username","password","mail.xxx.com");
   //订阅异步事件
   a.pop1.messagesreceiveasync += new microshaoft.njmail.pop3.messageseventhandler(a.pop1_messagesreceiveasync);
   a.pop1.attachmentsreceiveasync += new microshaoft.njmail.pop3.attachmentseventhandler(a.pop1_attachmentsreceiveasync);
   //订阅同步事件
   a.pop1.messagereceived += new microshaoft.njmail.pop3.messageseventhandler(a.pop1_messagereceived);
   a.pop1.attachmentreceive += new microshaoft.njmail.pop3.attachmentseventhandler(a.pop1_attachmentreceive);
   a.pop1.messagereceive += new microshaoft.njmail.pop3.messageseventhandler(a.pop1_messagereceive);
   //订阅 exception 事件
   a.pop1.attachmentexception += new microshaoft.njmail.pop3.attachmentseventhandler(a.pop1_attachmentexception);
   a.run();
   system.timers.timer t = new system.timers.timer();
   t.interval = 1000 * 30; //每 30 秒收取一次邮件
   t.enabled = true;
   t.elapsed += new system.timers.elapsedeventhandler(a.t_elapsed);
   while (system.console.readline().tolower() != "exit")
   {
    system.console.writeline("press /"exit/" to exit this programe!");
   }
  }

  private void t_elapsed(object sender, system.timers.elapsedeventargs e)
  {
   this.run();
  }

  private void run()
  {
   if (!isbusy)
   {
    system.console.writeline("busy");
    this.isbusy = true;
    //this.pop1.execute(true); //异步执行
    this.pop1.execute(); //同步执行
    this.isbusy = false;
    system.console.writeline("idle");
    system.console.writeline("press /"exit/" to exit this programe!");
   }
  }

  private void pop1_messagesreceiveasync(messagesstate omessagesstate)
  {
   system.console.writeline("message: [{0}].{1} of {2} messages have been recieved! {3}",omessagesstate.messageid,omessagesstate.jmessage.subject,omessagesstate.jmessages.count - 1,omessagesstate.messagescount);
   if (omessagesstate.messagescount == 0)
   {
    system.console.writeline("all messages have been recieved!");
   }
  }

  private void pop1_attachmentsreceiveasync(attachmentsstate oattachmentsstate)
  {
  
   oattachmentsstate.savetofile(@"e:/jmailattachments/[" + system.guid.newguid().tostring() + "]." +  oattachmentsstate.filename);
   oattachmentsstate.filename = @"e:/jmailattachments/[" + system.guid.newguid().tostring() + "]." +  oattachmentsstate.filename;

   if (oattachmentsstate.attachmentscount == 0)
   {
    system.console.writeline("[{0}].{1} have been recieved!",oattachmentsstate.messagesstate.messageid,oattachmentsstate.messagesstate.jmessage.subject);
    //异步执行删除有错误
    //oattachmentsstate.messagesstate.deletesinglemessage(oattachmentsstate.messagesstate.messageid);
   }
   //oattachmentsstate.cancelcurrent = true;
  }

  private void pop1_messagereceived(messagesstate omessagesstate)
  {
   system.console.writeline("message: [{0}].{1} of {2} messages have been recieved! {3}",omessagesstate.messageid,omessagesstate.jmessage.subject,omessagesstate.jmessages.count - 1,omessagesstate.messagescount);
   //可以每收完一封邮件即删除
   //omessagesstate.deletesinglemessage(omessagesstate.messageid);
  }

  private void pop1_attachmentreceive(attachmentsstate oattachmentsstate)
  {
   //oattachmentsstate.cancelcurrent = true;
   oattachmentsstate.savetofile(@"e:/jmailattachments/[" + system.guid.newguid().tostring() + "]." +  oattachmentsstate.filename);
   oattachmentsstate.filename = @"e:/jmailattachments/[" + system.guid.newguid().tostring() + "]." +  oattachmentsstate.filename;
   //oattachmentsstate.cancelcurrent = true;
  }

  private void pop1_messagereceive(messagesstate omessagesstate)
  {
   //omessagesstate.cancelcurrent = false;
  }

  private void pop1_attachmentexception(microshaoft.njmail.attachmentsstate oattachmentsstate)
  {
   system.console.writeline("execute exception: {0}",oattachmentsstate.exception.message);
   oattachmentsstate.filename ="e://temp//copy of " + oattachmentsstate.jattachment.name;
   oattachmentsstate.exceptionaction = microshaoft.njmail.exceptionactions.retry; //上一句文件改名后重新处理
   oattachmentsstate.exceptionaction = microshaoft.njmail.exceptionactions.ignore; //处理下一个附件
   //oattachmentsstate.exceptionaction = microshaoft.njmail.exceptionactions.throw;
  }
 }
}

//================================================================================================
// windows 测试程序:
namespace windowsapplicationtest
{
 using system;
 using system.windows.forms;
 /// <summary>
 /// form1 的摘要说明。
 /// </summary>
 public class form1 : system.windows.forms.form
 {
  private system.windows.forms.button button1;
  private system.windows.forms.timer timer1;
  private system.componentmodel.icontainer components;

  public form1()
  {
   //
   // windows 窗体设计器支持所必需的
   //
   initializecomponent();

   //
   // todo: 在 initializecomponent 调用后添加任何构造函数代码
   //
  }

  /// <summary>
  /// 清理所有正在使用的资源。
  /// </summary>
  protected override void dispose( bool disposing )
  {
   if( disposing )
   {
    if (components != null)
    {
     components.dispose();
    }
   }
   base.dispose( disposing );
  }

  #region windows 窗体设计器生成的代码
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void initializecomponent()
  {
   this.components = new system.componentmodel.container();
   this.button1 = new system.windows.forms.button();
   this.timer1 = new system.windows.forms.timer(this.components);
   this.suspendlayout();
   //
   // button1
   //
   this.button1.location = new system.drawing.point(24, 24);
   this.button1.name = "button1";
   this.button1.size = new system.drawing.size(80, 40);
   this.button1.tabindex = 0;
   this.button1.text = "button1";
   this.button1.click += new system.eventhandler(this.button1_click);
   //
   // timer1
   //
   this.timer1.tick += new system.eventhandler(this.timer1_tick);
   //
   // form1
   //
   this.autoscalebasesize = new system.drawing.size(6, 14);
   this.clientsize = new system.drawing.size(292, 273);
   this.controls.add(this.button1);
   this.name = "form1";
   this.text = "form1";
   this.resumelayout(false);

  }
  #endregion

  /// <summary>
  /// 应用程序的主入口点。
  /// </summary>
  [stathread]
  public static void main0() //main() //若要单独的 windows 程序可再换回 main()
  {
   application.run(new form1());
  }
  private microshaoft.njmail.pop3 x;
  private void button1_click(object sender, system.eventargs e)
  {
   button1.enabled = false;
   x = new microshaoft.njmail.pop3("username","password","mail.xxx.com");
   x.messagereceive += new microshaoft.njmail.pop3.messageseventhandler(x_messagereceive);
   x.messagereceived += new microshaoft.njmail.pop3.messageseventhandler(x_messagereceived);
   x.attachmentreceive += new microshaoft.njmail.pop3.attachmentseventhandler(x_attachmentreceive);
   x.attachmentexception += new microshaoft.njmail.pop3.attachmentseventhandler(x_attachmentexception);
   timer1.interval = 1000 * 120; //每 120 秒收取一次邮件
   timer1.enabled = false;
   x.execute();
   button1.enabled = true;
  }

  private void x_messagereceive(microshaoft.njmail.messagesstate omessagesstate)
  {
   //system.windows.forms.messagebox.show(omessagesstate.messageid.tostring());
   system.console.writeline("{0},《{1}》",omessagesstate.messageid.tostring(),omessagesstate.jmessage.subject);
 
   //system.console.writeline(omessagesstate.jmessage.body);
   //system.console.writeline(omessagesstate.jmessage.text);

  }

  private void timer1_tick(object sender, system.eventargs e)
  {
   x.execute();
  }

  private void x_messagereceived(microshaoft.njmail.messagesstate omessagesstate)
  {
   if (omessagesstate.messagescount == 0)
   {
    //system.windows.forms.messagebox.show("game over");
   }
   else
   {
    system.console.writeline(omessagesstate.messageid.tostring());
   }
  }

  private void x_attachmentreceive(microshaoft.njmail.attachmentsstate oattachmentsstate)
  {
   oattachmentsstate.filename = "e://temp//" + oattachmentsstate.filename;
   oattachmentsstate.savetofile(oattachmentsstate.filename);
   if (oattachmentsstate.exception != null)
   {
    throw oattachmentsstate.exception ;
   }

   oattachmentsstate.cancelcurrent = true; //不save处理当前附件
   if (oattachmentsstate.attachmentscount == 0)
   {
    //system.windows.forms.messagebox.show(oattachmentsstate.messagesstate.jmessage.attachments.count.tostring());
   }
   else
   {
    system.console.writeline(oattachmentsstate.attachmentid.tostring());
   }
  }

  private void x_attachmentexception(microshaoft.njmail.attachmentsstate oattachmentsstate)
  {
   system.console.writeline("execute exception: {0}",oattachmentsstate.exception.message);
   oattachmentsstate.filename ="e://temp//copy of " + oattachmentsstate.jattachment.name;
   //oattachmentsstate.exceptionaction = microshaoft.njmail.exceptionactions.retry; //上一句文件改名后重新处理
   oattachmentsstate.exceptionaction = microshaoft.njmail.exceptionactions.ignore; //处理下一个附件
   //oattachmentsstate.exceptionaction = microshaoft.njmail.exceptionactions.throw;
  }
 }
}

 

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表