Thursday, November 10, 2011

Update contacts/DL in outlook using Jacob

Yesterday i blogged about how to access contacts ( Distribution list as well) using Jacob here. Today i will explain how to create new contacts in outlook.
Its same except few deviations:

Creating contact or DL is fairly simple.

Here we are creating a simple contact. Defining variant(2) ensures that item created is a contact item and not DL.

Dispatch createItem = Dispatch.call((Dispatch)oOutlook, "CreateItem", new Variant(2)).toDispatch(); 

We can add values to different attributes. Here i am just adding FullName. We can add other values as well in similar fashion.
Dispatch.put(createItem, "FullName", "NEW CONTACT");  

Saving the item in outlook.
Dispatch.call(createItem, "Save");


in order to create DL, change required is that we need to use Variant(7),
Dispatch createItem = Dispatch.call((Dispatch)oOutlook, "CreateItem", new Variant(7)).toDispatch(); 


then we can set DL specific properties as below:
Dispatch.put(createItem, "DLName", "NEW DL");  


So we are now done with creating contacts. In case we are creating DL, just creating empty DL wont suffice. We need to add members to it.
There are two approaches which can be followed to add member:

  • one is adding single member
  • or adding bulk members together
Here is the code snippet to add single member in DL:

We are creating a recipient in DL,
Dispatch recepient = Dispatch.call((Dispatch)oNameSpace, "CreateRecipient", "abc@gmail.com").toDispatch(); 

Its mandatory to resolve the recipient otherwise it wont be added in DL. resolving means that the address given should be a valid email address, it might not be an existing address but it should compile to the rules of a valid email address
Dispatch.call(recepient,"Resolve");

Now we are adding recipient just created to the DL and saving it.
Dispatch.call(createItem, "AddMember", recepient);
Dispatch.call(createItem, "Save");

We can also add multiple members together to a DL:

Here we are creating a new Item which will hold a list of all recipients:

Dispatch createItem1 = Dispatch.call((Dispatch)oOutlook, "CreateItem", new Variant(0)).toDispatch(); 
Dispatch recepients = Dispatch.call(createItem1, "Recipients").toDispatch();

Add members to the recipient list:
Dispatch.call(recepients,"Add", "xyz@yahoo.com");

Dispatch.call(recepients,"Add", "abc@gmail.com");


Now as we added multiple members to list, we need to resolve all of them so instead of simple "Resolve" we will use "ResolveAll". it does the same job which resolve does for single item.
Dispatch.call(recepients,"ResolveAll");
Add all members to DL and save it.
Dispatch.call(createItem, "AddMembers", recepients);
Dispatch.call(createItem, "Save");

So this way we can create new items in outlook. Jacob is very powerful tool to access different Microsoft applications and work with them. Dispatch class provides the method to call native vba methods.

No comments:

Post a Comment