Thursday, November 10, 2011

Accessing Outlook contacts using JACOB

Here i will show how to access outlook components using JACOB. You can get brief idea of JACOB here.

I have developed the code to access and create contacts:

this code gives the handle of the outlook application.
ActiveXComponent component = new ActiveXComponent("Outlook.Application");
Dispatch oOutlook = component.getObject();



We are creating a session or namespace of the outlook to perform all the operations.
Object oNameSpace = component.getProperty("Session").toDispatch();

each folder in outlook is designated by a particular integer value. We need to provide that integer value in order to access it. Contacts folder has integer value 10 while inbox has integer value 6. Dispatch class internally makes a JNI call in order to execute this operation on MS application.

Dispatch contacts = Dispatch.call((Dispatch) oNameSpace,
"GetDefaultFolder", new Integer(10)).toDispatch();

If translated to VB, above code will look like,
oNameSpace.GetDefaultFolder(10);


So Jacob package just reads the class name, function name and attributes to be passed to function and makes a native call to dll.

Here we are creating an item in Contacts folder. Now Variant(2) tells the type of item to be created. To create a contact variant should be 2 while to create distribution list it should be 7.
Dispatch createItem = Dispatch.call((Dispatch)oOutlook, "CreateItem", new Variant(2)).toDispatch(); 


Here we are just adding name to the contact and saving it in outlook.
Dispatch.put(createItem, "FullName", "NEW CONTACT");
Dispatch.call(createItem, "Save");

Once done you can see the new contact being created in outlook contacts.

Similarly we can create Distribution list in outlook just using Variant value 7 as below:
Dispatch createItem = Dispatch.call((Dispatch)oOutlook, "CreateItem", new Variant(7)).toDispatch(); 


Also as Fullname is not an attribute of Distribution list we can specify the name of the DL and save it in outlook as below:

Dispatch.put(createItem, "DLName", "NEW DL");
Dispatch.call(createItem, "Save");


3 comments:

  1. Could you please suggest a way to login to any email account using jacob, or to access exchange server accounts directly, would really appreciate ur help on this, thanks John

    ReplyDelete
  2. Hi,
    I am creating a JAVA application to download attachments from received mails through outlook (I can not directly connect to the exchange server and hence the client to client approach), can it be done using JCOB?...if yes how?..

    ReplyDelete
  3. Hi, thanks for the post!
    Where could one look up what constants are accepted in the Dispatch.call and Dispatch.get methods? ... When I try something new I always get exception. I tried to use the MAPI reference but those calls are not accepted either...

    Thank a lot!

    ReplyDelete