0
votes

I have a google app script that collects new member registration from a form and adds the member email address to a google group.

the problem is that, sometimes, even though the address is legal, for ex. "[email protected]" the address does not exists. when I use the AdminDirectory.Members.insert(member, 'GroupName@GroupDomain') it will return error "resource not found". which I want to avoid in advance.

The question is how can I validate the email address to be an existing email address in advance by using a script command or library

I am using the following code:

function AddNewMember(LastEntryMail) { var NewMember = { email: LastEntryMail,
role: 'MEMBER' }; var MemberExist = false; var pageToken, page; var groupEmail = 'mygroupname@mygroupdomain'; var groupDomainName = 'mygroupdomain';

do 
{
  page = AdminDirectory.Members.list(groupEmail,{
  domain: groupDomainName,
  orderBy: 'Email',
  maxResults: 200,
  pageToken: pageToken
  });
  var GroupMembers = page.members;
  for (var m in GroupMembers) 
  {
    var email = GroupMembers[m].email;
    if(email == LastEntryMail)     
    {
      MemberExist = true;
      break; //stop the for loop
    }
  }
  if(MemberExist == true)
  {
   break; //stop the do loop
  }
  else //new member email was not found in current page members list. go to next page
  {
   pageToken = page.nextPageToken;
  }
} while (pageToken);

if(MemberExist == false)
{
  AdminDirectory.Members.insert(NewMember, groupEmail);
}

}

I know that I can catch the errors but I want to try and avoid errors as each error invokes the automatic mails etc...

1
For future reference, there's a google-apps-script tag that you can use for questions on this topic. I've added it this time :) - Joe Clay
Thanks but I am looking for a way to avoid the error before calling the AdminDirectory.Members.insert... - assaf
posted a more clear question here: stackoverflow.com/questions/42945872/… thanks - assaf

1 Answers

0
votes

You can use a try and catch block to detect the error and handle the error programmatically. In essence you are checking if the email exists or not. If you catch an error, it means that the email id doesn't exists. Your code will look something this:

try{
AdminDirectory.Members.Insert(members,email) 
//Enter any other code that uses email in here
}

catch (err){
Logger.log(err.message)
// Run this code when the email address doesn't exist
//You can check for specific err.message=='specific error string' and handle them appropriately
// Else throw the error using throw(err) statement
}

You can find more details here: https://www.w3schools.com/js/js_errors.asp