谷歌应用程序脚本检查是否存在电子邮件地址

时间:2017-03-20 13:38:00

标签: javascript google-apps-script

我有一个谷歌应用程序脚本,从表单收集新会员注册,并将成员电子邮件地址添加到谷歌组。

问题是,有时,即使地址合法,例如。 “jhon.doe@gmail.com”地址不存在。当我使用 AdminDirectory.Members.insert(成员,'GroupName @ GroupDomain')时,它将返回错误“找不到资源”。我想提前避免。

问题是如何使用脚本命令或库提前验证电子邮件地址是否为现有电子邮件地址

我使用以下代码:

function AddNewMember(LastEntryMail) {     var NewMember =         {          电子邮件:LastEntryMail,
         角色:'会员'         };     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);
}

}

我知道我可以捕获错误,但我想尝试避免错误,因为每个错误都会调用自动邮件等...

1 个答案:

答案 0 :(得分:0)

您可以使用try和catch块来检测错误并以编程方式处理错误。实质上,您正在检查电子邮件是否存在。如果您发现错误,则表示电子邮件ID不存在。您的代码看起来像这样:

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
}

您可以在此处找到更多详细信息:https://www.w3schools.com/js/js_errors.asp