Skip to main content

Importing and Synchronizing Contacts from a CSV (Outlook Express Export) into Exchange 2007 (private Contacts Folder or Public Contacts Folder) using

Following on from last week I’m going to put the Sync function I created into use and also show you how to create a contact in Powershell with a few lines of code using some wrappered EWS code I’ve put into my EWSUtil powershell library. I’ve also include some code to create a grouped list of contacst flagged with a custom property to allow full sync eg create if don’t exist create , delete if deleted from the syncfile and do property level changes if phone, address of name information is modified. I’ve used a csv file generated by doing an export in Outlook Express but this could be any csv file from any source.
Before we can use this process we need to set the target folder to where the contacts will be imported to or where the contacts we are going to sync with are located. For a local users contact folder something like this is needed.
$lcLocalContactFolderid = new-object EWSUtil.EWS.DistinguishedFolderIdType$lcLocalContactFolderid.Id = [EWSUtil.EWS.DistinguishedFolderIdNameType]::contacts
$mbMailbox = new-object EWSUtil.EWS.EmailAddressType
$mbMailbox.EmailAddress = “
$dTypeFld.Mailbox = $mbMailbox
$lcLocalContacts = $ewc.getfolder($lcLocalContactFolderid)
If you want to target a Public folder it’s not just as easy as putting in the path to the folder we need to get the code to traverse that folder path and find the target folder. The method I use is to input a normal folder path the split this into an array and then starting at the root use a separate find folder on each parent folder in the dimensioning hierarchy this is a little hard to explain but the code explains it better.
$pfPublicFolderPath = "/PubContacts/SyncContacts"
$parentFolder = new-object EWSUtil.EWS.DistinguishedFolderIdType
$parentFolder.Id = [EWSUtil.EWS.DistinguishedFolderIdNameType]::publicfoldersroot
$fldarry = new-object EWSUtil.EWS.BaseFolderIdType[] 1
$fldarry[0] = $parentFolder
$rfRootFolder = $ewc.getFolder($fldarry)
$pfArray = $pfPublicFolderPath.Split("/")
$cfContactsFolder = $rfRootFolder[0]
for ($lint = 1; $lint -lt $pfArray.Length; $lint++) {
$cfContactsFolder = $ewc.FindSubFolder($cfContactsFolder, $pfArray[$lint]);
Once we have our target folder we can do a number of things before going into synchronization I want to show some easy code for creating contacts using EWS from Powershell. To create a contact we really only need a csv file with 2 columns one for the name and one for the emailAddress eg
Fred FlintStone,
Barney Rubble,
If you have a csv file that you want to import into a local users contacts folder first we need to create an Exchange Web Services Connection so we can use EWS and get the target folder as I’ve talked about above. Once this is done you can then read the csv file using the Import-csv powershell cmdlet. We then loop through each line of the csv file and create contacts from the information within. When creating a contact there are several properties you do need to set such as some Extended mapi properties that aren’t included in the EWS contactType class. These represent the displayName for emailaddress's also you need to make sure you set the FileAs and Subject properties so the contact will display correctly in Outlook and the address book. So the simplest code to create contacts from a 2 column csv file would look like (I’ve omitted the connect and folder find functions which I’ll include in the download im also splitting the name into to an array to fill in the firstname and surname properties).
import-csv $fnFileName | foreach-object{
$newcontact = new-object EWSUtil.EWS.ContactItemType
$namearray = $_.Name.split(" ")
$newcontact.GivenName = $namearray[0]
$newcontact.Surname = $namearray[1]
$newcontact.Subject = $_.Name
$newcontact.FileAs = $_.Name
$newcontact.DisplayName = $_.Name
$newcontact.EmailAddresses = new-object EWSUtil.EWS.EmailAddressDictionaryEntryType[] 1
$newcontact.EmailAddresses[0] = new-object EWSUtil.EWS.EmailAddressDictionaryEntryType
$newcontact.EmailAddresses[0].Key = [EWSUtil.EWS.EmailAddressKeyType]::EmailAddress1
$newcontact.EmailAddresses[0].Value = $_.EmailAddress

$dnEmailDisplayName1 = new-object EWSUtil.EWS.PathToExtendedFieldType
$dnEmailDisplayName1.DistinguishedPropertySetIdSpecified = $true
$dnEmailDisplayName1.DistinguishedPropertySetId = [EWSUtil.EWS.DistinguishedPropertySetType]::Address
$dnEmailDisplayName1.PropertyId = 32896
$dnEmailDisplayName1.PropertyIdSpecified = $true
$dnEmailDisplayName1.PropertyType = [EWSUtil.EWS.MapiPropertyTypeType]::String

$daEmailDisplayName1 = new-object EWSUtil.EWS.PathToExtendedFieldType
$daEmailDisplayName1.DistinguishedPropertySetIdSpecified = $true
$daEmailDisplayName1.DistinguishedPropertySetId = [EWSUtil.EWS.DistinguishedPropertySetType]::Address
$daEmailDisplayName1.PropertyId = 32900
$daEmailDisplayName1.PropertyIdSpecified = $true;
$daEmailDisplayName1.PropertyType = [EWSUtil.EWS.MapiPropertyTypeType]::String

$atEmailAddressType1 = new-object EWSUtil.EWS.PathToExtendedFieldType
$atEmailAddressType1.DistinguishedPropertySetIdSpecified = $true
$atEmailAddressType1.DistinguishedPropertySetId = [EWSUtil.EWS.DistinguishedPropertySetType]::Address
$atEmailAddressType1.PropertyId = 32898
$atEmailAddressType1.PropertyIdSpecified = $true;
$atEmailAddressType1.PropertyType = [EWSUtil.EWS.MapiPropertyTypeType]::String

$newcontact.ExtendedProperty = new-object EWSUtil.EWS.ExtendedPropertyType[] 3
$newcontact.ExtendedProperty[0] = new-object EWSUtil.EWS.ExtendedPropertyType
$newcontact.ExtendedProperty[0].ExtendedFieldURI = $dnEmailDisplayName1
$newcontact.ExtendedProperty[0].Item = $_.Name + " (" + $_.EmailAddress + ")"

$newcontact.ExtendedProperty[1] = new-object EWSUtil.EWS.ExtendedPropertyType
$newcontact.ExtendedProperty[1].ExtendedFieldURI = $daEmailDisplayName1
$newcontact.ExtendedProperty[1].Item = $_.EmailAddress

$newcontact.ExtendedProperty[2] = new-object EWSUtil.EWS.ExtendedPropertyType
$newcontact.ExtendedProperty[2].ExtendedFieldURI = $atEmailAddressType1
$newcontact.ExtendedProperty[2].Item = "SMTP"



Okay now we can create contacts syncronizing is just matter of using the same logic and adding some code that before creating the contacts checks to see if it exists and if it does then does a property level check of the contact and then updates any information that has changed or does nothing at all. To facilite this i've made a few changes to the code above first i've added a custom Mapi property to mark any contacts that are created with this process. then when it comes time to syncronise i have a function that first finds all the contacts that this process has created when (or if) it had run before. This function returns a Hashtable indexed by the Email address so it makes it easy to check if the contact has already been created and determines if the sync needs to be run for changed properties. On the back side contacts can also be deleted if they no longer exist in the file
So the Full sync,add,delete logic would look like
$_."E-mail Address"
if ($contactsHash.containskey($_."E-mail Address")){
"Address Exist Test Sync"
$dsContact = $contactsHash[$_."E-mail Address"]
$diffs = $ewc.DiffConact($newcontact,$dsContact)
if ($diffs.Count -ne 0){
"Number Changes Found " + $diffs.Count

$ewc.AddNewContact($newcontact,$cfContactsFolder.FolderId )

$diDelCollection = @()
$delitems = $false
foreach ($key in $contactsHash.Keys){
if ($fileContactsHash.ContainsKey($key) -eq $false){
$diDelCollection += $contactsHash[$key]
$delitems = $true

if ($delitems -eq $true){
$delbis = new-object EWSUtil.EWS.BaseItemIdType[] $diDelCollection.length
for($delint=0;$delint -lt [Int]$diDelCollection.length;$delint++){
$delbis[$delint] = $diDelCollection[$delint].ItemId}

"Items Deleted"
In the download i've create a sample that uses an Outlook Express Address Book csv Export with all the fields ticked that imports and syncronzes with a public Contacts folders as well as the Local contacts import sample I've talked about. I've put the download here. To use these scrripts you need to use the latest EWSUtil Powershell library which you can download from
For more information on using the library and connection and authentication options this is documented in another post

Popular posts from this blog

Using the MSAL (Microsoft Authentication Library) in EWS with Office365

Last July Microsoft announced here they would be disabling basic authentication in EWS on October 13 2020 which is now a little over a year away. Given the amount of time that has passed since the announcement any line of business applications or third party applications that you use that had been using Basic authentication should have been modified or upgraded to support using oAuth. If this isn't the case the time to take action is now. When you need to migrate a .NET app or script you have using EWS and basic Authentication you have two Authentication libraries you can choose from ADAL - Azure AD Authentication Library (uses the v1 Azure AD Endpoint) MSAL - Microsoft Authentication Library (uses the v2 Microsoft Identity Platform Endpoint) the most common library you will come across in use is the ADAL libraries because its been around the longest, has good support across a number of languages and allows complex authentications scenarios with support for SAML etc. The

How to test SMTP using Opportunistic TLS with Powershell and grab the public certificate a SMTP server is using

Most email services these day employ Opportunistic TLS when trying to send Messages which means that wherever possible the Messages will be encrypted rather then the plain text legacy of SMTP.  This method was defined in RFC 3207 "SMTP Service Extension for Secure SMTP over Transport Layer Security" and  there's a quite a good explanation of Opportunistic TLS on Wikipedia .  This is used for both Server to Server (eg MTA to MTA) and Client to server (Eg a Message client like Outlook which acts as a MSA) the later being generally Authenticated. Basically it allows you to have a normal plain text SMTP conversation that is then upgraded to TLS using the STARTTLS verb. Not all servers will support this verb so if its not supported then a message is just sent as Plain text. TLS relies on PKI certificates and the administrative issue s that come around certificate management like expired certificates which is why I wrote th

A walk-though using the Graph API Mailbox reports in Powershell

Quite recently the Reporting side of the Graph API has moved in GA from beta, there are quite a number of reports that can be run across various Office365 surfaces but in this post I'm going to focus on the Mailbox related ones. Accessing Office365 Reports using Powershell is nothing new and has been available in the previous reporting endpoint however from the end of January many of these cmdlets are now being depreciated in favour of the Graph API . Prerequisites  In comparison to using the Remote PowerShell cmdlets where only the correct Office365 Admin permissions where needed, to use the new Graph API reports endpoint you need to use OAuth for authentication so this requires an Application Registration  that is then given the correct oAuth Grants to use the Reports EndPoin
All sample scripts and source code is provided by for illustrative purposes only. All examples are untested in different environments and therefore, I cannot guarantee or imply reliability, serviceability, or function of these programs.

All code contained herein is provided to you "AS IS" without any warranties of any kind. The implied warranties of non-infringement, merchantability and fitness for a particular purpose are expressly disclaimed.