繁体   English   中英

在 Google Apps 脚本中检查电子邮件是否有效

[英]Checking if an email is valid in Google Apps Script

我正在使用内置的 api 针对 Google 电子表格编写脚本来发送一些预订确认,目前如果有人填写了无效的电子邮件,我的脚本就会中断。 我希望它只是将一些数据保存到尚未收到通知的客人列表中,然后继续循环浏览预订。

这是我当前的代码(简化):

// The variables email, subject and msg are populated.
// I've tested that using Browser.msgBox(), and the correct column values are
// found and used

// The script breaks here, if an incorrect email address has been filled in
MailApp.sendEmail(email, subject, msg)

根据 文档MailApp类上仅有的两种方法是发送电子邮件和检查每日配额——与检查有效电子邮件地址无关——所以我真的不知道该类必须满足什么标准才能接受请求,因此无法编写验证例程。

如果您需要事先验证电子邮件地址,请在您的驱动器中创建一个空白电子表格。 然后,运行下面的函数,将testSheet变量更改为指向您创建的电子表格。 该函数将执行一个简单的正则表达式测试以捕获格式错误的地址,然后通过尝试将其临时添加为电子表格中的查看器来检查该地址是否实际有效。 如果地址可以添加,它必须是有效的。

function validateEmail(email) {
  var re = /\S+@\S+\.\S+/;
  if (!re.test(email)) {
    return false;
  } else {
    var testSheet = SpreadsheetApp.openById(arbitrarySpreadsheetInYourDrive);
    try {
      testSheet.addViewer(email);
    } catch(e) {
      return false;
    }
    testSheet.removeViewer(email);
    return true;
  }
}

来自如何在 JavaScript 中验证电子邮件地址的正则表达式

保持冷静,捕捉并记录异常并继续:

try {
  // do stuff, including send email
  MailApp.sendEmail(email, subject, msg)
} catch(e) {
  Logger.log("Error with email (" + email + "). " + e);
}

另一方面,避免在脚本中检查电子邮件并摆脱丢失配额或 try-catch 等。我使用当用户尝试发送电子邮件时,我收到了一个有效的电子邮件,通过在电子邮件中签名并收到该电子邮件:

private void handleSignInResult(Task<GoogleSignInAccount> completedTask) {
    try {
        GoogleSignInAccount account = completedTask.getResult(ApiException.class);

       String s = account.getEmail(); // here is the valid email.
                       
    } catch (ApiException e) {
        // The ApiException status code indicates the detailed failure reason.
        // Please refer to the GoogleSignInStatusCodes class reference for more information.
        Log.w(TAG, "signInResult:failed code=" + e.getStatusCode());
       
    }
}

完整程序在这里。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM