Tech Blog

Change Preferred Email Address

If you want to send notifcations out to a set of patrons but would like them to go to the non-preferred email address the GET and PUT methods can be used on the users API. The following code reads a list of usernames in a text file then makes a GET request for each user record, this returns the data in JSON which is copied to a temporary file, if the patron record has 2 emails the non-preferred one is made preferred and the other not preferred. The changed values are then sent bakc to Alma using a PUT request.

#text file containing list of usernames who the preferred email address needs to be changed to the personal address
$UsersFile = "users.txt"
#sandbox users read/write key
$apiKey = "XXXXXXXX"
#grab users from file
$UsersList = Get-Content $UsersFile -ErrorAction SilentlyContinue

#iterate over each user in file

foreach ($user in $UsersList) {

#clear contents of temp file used to store individual user record in json
Clear-Content "temp_file.json"

#do get to get user details
$getUrl = "$user`?apikey=$apikey&user_id_type=all_unique&send_pin_number_letter=false&recalculate_roles=false"
$json = Invoke-RestMethod -Method get -Uri $getUrl -ContentType 'application/json' -Headers @{"accept"="application/json"}
#check that user has 2 emails, if 2 then proceed to sway preferred addresses over
$check_for_second_email = $
if($check_for_second_email -gt 1){
#write-host ($check_for_second_email)
$first_email = $[0].preferred
$seccond_email = $[1].preferred
if ($first_email -eq 'True'){
$[0].preferred = 'False'
$[1].preferred = 'True'

if ($seccond_email -eq 'True'){
$[1].preferred = 'False'
$[0].preferred = 'True'


ConvertTo-json -InputObject ($json) -Depth 99|Out-File "temp_file.json"


#grab amended data from temp file
$data_to_post = Get-Content "temp_file.json"

#PUT the user json back into Alma with preferred email changed

$putUrl = "$user`?apikey=$apikey&user_id_type=all_unique&send_pin_number_letter=false&recalculate_roles=false"
$response = Invoke-RestMethod -Method PUT -Uri $putUrl -Body $data_to_post -ContentType 'application/json'
#clear contents of temp file for next iteration
Clear-Content "temp_file.json"


Leave a Reply