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 = “
user@domain.com
$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
Name,EmailAddress
Fred FlintStone,Fred@slate.com
Barney Rubble,barney@slate.com
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"

$_.EmailAddress

$ewc.AddNewContact($newcontact,$lcLocalContacts[0].FolderId)

}
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
[VOID]$ewc.UpdateContact($diffs,$dsContact.ItemId)
}

}else{
"CreateContact"
$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++){
$diDelCollection[$delint].Subject.ToString()
$delbis[$delint] = $diDelCollection[$delint].ItemId}

$delbis
$ewc.DeleteItems($delbis,[EWSUtil.EWS.DisposalType]::SoftDelete)
"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 https://github.com/gscales/Powershell-Scripts/raw/master/ScriptArchive/.
For more information on using the library and connection and authentication options this is documented in another post

Popular posts from this blog

Testing and Sending email via SMTP using Opportunistic TLS and oAuth in Office365 with PowerShell

As well as EWS and Remote PowerShell (RPS) other mail protocols POP3, IMAP and SMTP have had OAuth authentication enabled in Exchange Online (Official announcement here ). A while ago I created  this script that used Opportunistic TLS to perform a Telnet style test against a SMTP server using SMTP AUTH. Now that oAuth authentication has been enabled in office365 I've updated this script to be able to use oAuth instead of SMTP Auth to test against Office365. I've also included a function to actually send a Message. Token Acquisition  To Send a Mail using oAuth you first need to get an Access token from Azure AD there are plenty of ways of doing this in PowerShell. You could use a library like MSAL or ADAL (just google your favoured method) or use a library less approach which I've included with this script . Whatever way you do this you need to make sure that your application registration  https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-

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  https://en.wikipedia.org/wiki/Opportunistic_TLS .  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

The MailboxConcurrency limit and using Batching in the Microsoft Graph API

If your getting an error such as Application is over its MailboxConcurrency limit while using the Microsoft Graph API this post may help you understand why. Background   The Mailbox  concurrency limit when your using the Graph API is 4 as per https://docs.microsoft.com/en-us/graph/throttling#outlook-service-limits . This is evaluated for each app ID and mailbox combination so this means you can have different apps running under the same credentials and the poor behavior of one won't cause the other to be throttled. If you compared that to EWS you could have up to 27 concurrent connections but they are shared across all apps on a first come first served basis. Batching Batching in the Graph API is a way of combining multiple requests into a single HTTP request. Batching in the Exchange Mail API's EWS and MAPI has been around for a long time and its common, for email Apps to process large numbers of smaller items for a variety of reasons.  Batching in the Graph is limited to a m
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.