首页  编辑  

Jacob读取Outlook邮件/Java中操作OLE Activex/Automation对象

Tags: /Java/   Date Created:

Jacob输出Outlook邮件内容

  • 下载 jacob-1.20.zip,解压后,把 jacob.jar 导入Java工程,把 jacob-1.20-x64.dll和jacob-1.20-x86.dll,放到系统目录或者程序所在目录或者任意PATH环境变量路径下即可。
  • 下载示例源码:jacob-project.zip
  • 用IDEA打开源码工程目录,然后找到 Outlook.java,运行后即可扫描Outlook所有账户和文件夹,并列出每个文件夹的第一封邮件,输出邮件主题和邮件内容。
参考链接:
package com.jacob.samples.outlook;

/**
 * JACOB Outlook sample contributed by
 * Christopher Brind <christopher.brind@morse.com> 
 */

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

/**
 * sample class to show simple outlook manipulation
 */
public class Outlook {

   private static String pad(int i) {
      StringBuffer sb = new StringBuffer();

      while (sb.length() < i) {
         sb.append(' ');
      }

      return sb.toString();
   }

   private static void recurseFolders(int iIndent, Dispatch o) {

      if (o == null) {
         return;
      }
      Dispatch oFolders = Dispatch.get(o, "Folders").toDispatch();
      // System.out.println("oFolders=" + oFolders);
      if (oFolders == null) {
         return;
      }

      Dispatch oFolder = Dispatch.get(oFolders, "GetFirst").toDispatch();
      do {
         Object oFolderName;
         try {
            oFolderName = Dispatch.get(oFolder, "Name");
            if (null == oFolderName) {
               break;
            }
         } catch (IllegalStateException e) {
            break;
         }

         System.out.println(pad(iIndent) + oFolderName);
         recurseFolders(iIndent + 3, oFolder);

         Dispatch items = Dispatch.get(oFolder, "Items").toDispatch();
         Dispatch item = Dispatch.get(items, "GetFirst").toDispatch();
         if (item != null) try {
            Object subject = Dispatch.get(item, "Subject");
            Object body = Dispatch.get(item, "Body");
            System.out.println(pad(iIndent) + "Mail: " + subject + "\nBody: " + body);
         } catch (Exception e) {

         }

         oFolder = Dispatch.get(oFolders, "GetNext").toDispatch();
      } while (true);
   }

   /**
    * standard run loop
    * 
    * @param asArgs
    *            command line arguments
    * @throws Exception
    */
   public static void main(String asArgs[]) throws Exception {
      System.out.println("Outlook: IN");

      ActiveXComponent axOutlook = new ActiveXComponent("Outlook.Application");
      try {
         System.out.println("version=" + axOutlook.getProperty("Version"));

         Dispatch oOutlook = axOutlook.getObject();
         System.out.println("version=" + Dispatch.get(oOutlook, "Version"));

         Dispatch oNameSpace = axOutlook.getProperty("Session").toDispatch();
         System.out.println("oNameSpace=" + oNameSpace);

         recurseFolders(0, oNameSpace);

      } finally {
         axOutlook.invoke("Quit", new Variant[] {});
      }
   }

}

jacob-1.20.zip (494.5KB)