JAVA MAIL DEMO1(copier、folderlist、monitor、mover)

在JAVA MAIL编程之后,需要在本地搭建一个附件服务器,我选择的是试用版的Magic Winmail,安装完成后注意保存相关的配置信息,本地的配置信息如下:
SMTP服务器地址:127.0.0.1
SMTP服务器端口:25
激活SMTP发信认证
POP3服务器地址:127.0.0.1
POP3服务器端口:110
POP3用户名:test
POP3密码:test
Webmail URL: [url]http://127.0.0.1:6080/[/url]
关于服务器端的一点说明:
创建一个 [email protected]帐号后,可以看到在服务器端看到如下文件结构:
file://D:\Program Files\Magic Winmail\server\store\test
│�lastvisit.dat
│�mailsize.dat
│�msgcache.dat
│�userinfo.dat
├─INBOX
│���1240110797.4044.3336,S=457.0.SR
│���1240111925.7727.2664,S=1080
├─Draft
│���1240111780.4.2970,S=372.0.U
├─Sent
│���1240111925.8422.2317,S=920.0.S
├─Spam
│���1240111888.1722.5222,S=5338
└─Trash
����1240111734.8162.7011,S=1609.0.S
这个树形结构表明 [email protected]文件夹分配及对应邮件数目:
收件箱(INBOX):2
草稿箱(Draft):1
已发送邮件(Sent):1
垃圾邮件(Spam):1
已删除邮件(Trash):1
 
本次的DEMO有:
1、copier:
   public static void copier() throws Exception {
    String src = "Spam";
    String dest = "MYDest";
    Session session = Session.getDefaultInstance(System.getProperties(), null);
     // 连接方式1:
     // Store store = session.getStore("imap");
     // store.connect("127.0.0.1", "test", "test");
     // 连接方式2:
    Store store = session.getStore( new URLName( "imap://test:[email protected]"));
    store.connect();

    System.out.println("Connected...");
    Folder folder = store.getFolder(src);
    folder.open(Folder.READ_WRITE);
    System.out.println("Opened source...");
    Folder dfolder = store.getFolder(dest);
    if (!dfolder.exists()) // create
      dfolder.create(Folder.HOLDS_MESSAGES);

    Message[] msgs = folder.getMessages();
    System.out.println("Got messages..." + msgs.length);

    // Copy messages into destination,
    folder.copyMessages(msgs, dfolder);
    System.out.println("Copied messages...");

    // Close the folder and store
    folder.close(false);
    store.close();
    System.out.println("Closed folder and store...");
  }
输出:
Connected...
Opened source...
Got messages...2
Copied messages...
Closed folder and store...
运行结果:
D:\Program Files\Magic Winmail\server\store\test>ls MYDest
1240111888.1722.5222,S=5338.9

D:\Program Files\Magic Winmail\server\store\test>ls Spam
1240111888.1722.5222,S=5338.1.U
 
2、folderlist:
   public static void folderlist() throws Exception {
    Properties props = System.getProperties();
    Session session = Session.getInstance(props, null);
    Store store = session.getStore( new URLName( "imap://test:[email protected]"));
    store.connect();
    Folder rf = store.getDefaultFolder();
    dumpFolder(rf, false, "");
    if ((rf.getType() & Folder.HOLDS_FOLDERS) != 0) {
      Folder[] f = rf.list("%");
      for (int i = 0; i < f.length; i++)
        dumpFolder(f[i], true, "        ");
    }
    store.close();

  }

  static void dumpFolder(Folder folder, boolean recurse, String tab) throws Exception {
    System.out.println(tab + "Name:            " + folder.getName());
    System.out.println(tab + "Full Name: " + folder.getFullName());
    System.out.println(tab + "URL:             " + folder.getURLName());

    if (!folder.isSubscribed())
      System.out.println(tab + "Not Subscribed");

    if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0) {
      if (folder.hasNewMessages())
        System.out.println(tab + "Has New Messages");
      System.out.println(tab + "Total Messages:    " + folder.getMessageCount());
      System.out.println(tab + "New Messages:        " + folder.getNewMessageCount());
      System.out.println(tab + "Unread Messages: " + folder.getUnreadMessageCount());
    }
    if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0)
      System.out.println(tab + "Is Directory");

    /*
     * Demonstrate use of IMAP folder attributes returned by the IMAP LIST
     * response.
     */
    if (folder instanceof IMAPFolder) {
      IMAPFolder f = (IMAPFolder) folder;
      String[] attrs = f.getAttributes();
      if (attrs != null && attrs.length > 0) {
        System.out.println(tab + "IMAP Attributes:");
        for (int i = 0; i < attrs.length; i++)
          System.out.println(tab + "        " + attrs[i]);
      }
    }
    System.out.println();

    if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) {
      if (recurse) {
        Folder[] f = folder.list();
        for (int i = 0; i < f.length; i++)
          dumpFolder(f[i], recurse, tab + "        ");
      }
    }
  }
输出:
Name:            
Full Name:    
URL:             imap://[email protected]/
Not Subscribed
Is Directory
IMAP Attributes:
        \Noselect

        Name:            Sent
        Full Name: Sent
        URL:             imap://[email protected]/Sent
        Not Subscribed
        Total Messages:    1
        New Messages:        0
        Unread Messages: 0
        Is Directory

        Name:            Draft
        Full Name: Draft
        URL:             imap://[email protected]/Draft
        Not Subscribed
        Total Messages:    1
        New Messages:        0
        Unread Messages: 1
        Is Directory

        Name:            Trash
        Full Name: Trash
        URL:             imap://[email protected]/Trash
        Not Subscribed
        Total Messages:    1
        New Messages:        0
        Unread Messages: 0
        Is Directory

        Name:            Spam
        Full Name: Spam
        URL:             imap://[email protected]/Spam
        Not Subscribed
        Has New Messages
        Total Messages:    1
        New Messages:        1
        Unread Messages: 1
        Is Directory

        Name:            MYDest
        Full Name: MYDest
        URL:             imap://[email protected]/MYDest
        Not Subscribed
        Total Messages:    0
        New Messages:        0
        Unread Messages: 0
        Is Directory

        Name:            INBOX
        Full Name: INBOX
        URL:             imap://[email protected]/INBOX
        Not Subscribed
        Total Messages:    2
        New Messages:        0
        Unread Messages: 0
        Is Directory
 
3、monitor:
   public static void monitor() throws Exception {
    Properties props = System.getProperties();
    Session session = Session.getInstance(props, null);
    Store store = session.getStore( new URLName( "imap://test:[email protected]"));
    store.connect();
    Folder folder = store.getFolder("INBOX");
    if (folder == null || !folder.exists()) {
      System.out.println("Invalid folder");
      System.exit(1);
    }
    folder.open(Folder.READ_WRITE);
    folder.addMessageCountListener(new MessageCountAdapter() {
      public void messagesAdded(MessageCountEvent ev) {
        Message[] msgs = ev.getMessages();
        System.out.println("Got " + msgs.length + " new messages");
        for (int i = 0; i < msgs.length; i++) {
          try {
            System.out.println("-----");
            System.out.println("Message " + msgs[i].getMessageNumber() + ":");
            msgs[i].writeTo(System.out);
          } catch (IOException ioex) {
            ioex.printStackTrace();
          } catch (MessagingException mex) {
            mex.printStackTrace();
          }
        }
      }
    });

    // Check mail once in "freq" MILLIseconds
    // 300毫秒检查一次
    int freq = 300;
    boolean supportsIdle = false;
    try {
      if (folder instanceof IMAPFolder) {
        IMAPFolder f = (IMAPFolder) folder;
        f.idle();
        supportsIdle = true;
      }
    } catch (FolderClosedException fex) {
      throw fex;
    } catch (MessagingException mex) {
      supportsIdle = false;
    }
    for (;;) {
      if (supportsIdle && folder instanceof IMAPFolder) {
        IMAPFolder f = (IMAPFolder) folder;
        f.idle();
        System.out.println("IDLE done");
      } else {
        Thread.sleep(freq); // sleep for freq milliseconds

        // This is to force the IMAP server to send us
        // EXISTS notifications.
        folder.getMessageCount();
      }
    }

  }
这个例子从输出来看,抛异常,不过暂时没有发现应该改进哪个地方:
Got 2 new messages
-----
Message 4:
Return-Path: < [email protected]>
Delivered-To: [email protected]
X-WM-Delivered: [email protected]
Received: from kinkding-d1d01d ([127.0.0.1])
  (envelope-sender < [email protected]>)
  by 127.0.0.1 with ESMTP
  for < [email protected]>; Sun, 19 Apr 2009 13:00:10 +0800
Date: Sun, 19 Apr 2009 13:00:10 +0800
From: "test2" < [email protected]>
To: "test" < [email protected]>
Subject: test
Message-ID: < [email protected]>
X-mailer: Foxmail 6, 14, 103, 24 [cn]
Mime-Version: 1.0
Content-Type: text/plain;
  charset="us-ascii"
Content-Transfer-Encoding: 7bit

2009-04-19    
-----
Message 5:
javax.mail.MessagingException: No content
  at com.sun.mail.imap.IMAPMessage.writeTo(IMAPMessage.java:672)
  at test.mail.MyTest$1.messagesAdded(MyTest.java:128)
  at javax.mail.event.MessageCountEvent.dispatch(MessageCountEvent.java:146)
  at javax.mail.EventQueue.run(EventQueue.java:130)
  at java.lang.Thread.run(Unknown Source)
Got 1 new messages
-----
Message 6:
javax.mail.MessagingException: No content
  at com.sun.mail.imap.IMAPMessage.writeTo(IMAPMessage.java:672)
  at test.mail.MyTest$1.messagesAdded(MyTest.java:128)
  at javax.mail.event.MessageCountEvent.dispatch(MessageCountEvent.java:146)
  at javax.mail.EventQueue.run(EventQueue.java:130)
  at java.lang.Thread.run(Unknown Source)
 
4、mover:
   public static void mover() throws Exception {
    Properties props = System.getProperties();
    Session session = Session.getInstance(props, null);
    Store store = session.getStore( new URLName( "imap://test:[email protected]"));
    store.connect();
    String src = "MYDest";
    String dest = "MYDest2";

    Folder folder = store.getFolder(src);
    if (folder == null || !folder.exists()) {
      System.out.println("Invalid folder: " + src);
      System.exit(1);
    }

    folder.open(Folder.READ_WRITE);

    int count = folder.getMessageCount();
    if (count == 0) { // No messages in the source folder
      System.out.println(folder.getName() + " is empty");
      folder.close(false);
      store.close();
      return;
    }
    Folder dfolder = store.getFolder(dest);
    if (!dfolder.exists())
      dfolder.create(Folder.HOLDS_MESSAGES);
    Message[] msgs = folder.getMessages();
    System.out.println("Moving " + msgs.length + " messages");

    if (msgs.length != 0) {
      folder.copyMessages(msgs, dfolder);
      folder.setFlags(msgs, new Flags(Flags.Flag.DELETED), true);

      // Dump out the Flags of the moved messages, to insure that
      // all got deleted
      for (int i = 0; i < msgs.length; i++) {
        if (!msgs[i].isSet(Flags.Flag.DELETED))
          System.out.println("Message # " + msgs[i] + " not deleted");
      }
    }
    
    // 此处设置为true,则src文件夹下面的记录会被删除,设置为false则不会删除。
    folder.close(true);
    store.close();
  }
输出:
Moving 1 messages
运行结果:
D:\Program Files\Magic Winmail\server\store\test>ls MYDest

D:\Program Files\Magic Winmail\server\store\test>ls MYDest2
1240111888.1722.5222,S=5338.1.U

你可能感兴趣的:(职场,休闲)