Reputation: 10794
function matchAndReplace(){
var oldDomain = "@olddomain.com";
var newDomain = "@newdomain.com";
// retrieve all the user's contacts
var contacts = ContactsApp.getContacts();
Logger.log('num '+contacts.length);
for (var i = 0; i < contacts.length; i++) {
var emails = contacts[i].getEmails();
Logger.log(emails.length+' emails');
for (var e in emails) {
var email = emails[e].getAddress();
//emails[e].setLabel(ContactsApp.Field.WORK_EMAIL);
Logger.log(email);
if (email.indexOf(oldDomain) !== -1) {
//remove
emails[e].deleteEmailField(); <-- error
Logger.log(email+' removed');
//add
var newEmail = email.split("@")[0]+newDomain;
var newEmailField = contacts[i].addEmail(ContactsApp.Field.WORK_EMAIL, newEmail);
Logger.log(newEmail+' added');
}
}
//break;
}
}
Error:
Service error: ContactsApp: Entry does not have any fields set. (line 20, file "Code")
Upvotes: 0
Views: 580
Reputation: 45710
You may be running into a transient service issue, because there's nothing obviously wrong with your code. You could improve its efficiency and eliminate all the delete / add operations, though, and that might reduce the possibility of the error.
Try this:
/**
* Find all contacts that have email addresses in the oldDomain,
* and change them to be the same ID in the newDomain.
*
* @param {String} oldDomain E.g. 'oldExample.com'
* @param {String} newDomain E.g. 'newExample.org'
*
* @returns {Number} Count of updated contacts.
*/
function migrateDomain(oldDomain, newDomain){
// Validate arguments
if (arguments.length !== 2) throw new Error( 'Missing arguments.');
oldDomain = '@' + oldDomain;
newDomain = '@' + newDomain;
// retrieve all the user's contacts that have email in oldDomain
var contacts = ContactsApp.getContactsByEmailAddress(oldDomain);
Logger.log('num '+contacts.length);
for (var i = 0; i < contacts.length; i++) {
var emails = contacts[i].getEmails();
Logger.log(emails.length+' emails');
for (var e=0; e<emails.length; e++) {
var email = emails[e].getAddress();
Logger.log(email);
if (email.indexOf(oldDomain) !== -1) {
// change
var newEmail = email.split("@")[0]+newDomain;
emails[e].setAddress(newEmail);
Logger.log(' changed to '+newEmail);
}
}
}
return i;
}
Upvotes: 1