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

发布于 2024-09-29 00:02:34 字数 623 浏览 2 评论 0原文

我正在使用内置 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 类上的任务是发送电子邮件并检查每日配额 - 与检查有效电子邮件地址无关 - 所以我真的不知道该类必须满足什么标准才能接受请求,并且因此无法编写验证例程。

I'm using the built-in api for scripting against Google Spreadsheets to send some booking confirmations, and currently my script breaks if someone has filled in an invalid email. I'd like it to just save some data to a list of guests that haven't been notified, and then proceed with looping through the bookings.

This is my current code (simplified):

// 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)

According to the documentation the only two methods on the MailApp class are to send emails and check the daily quota - nothing about checking for valid email addresses - so I don't really know what criteria must be fulfilled for the class to accept the request, and thus can't write a validation routine.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

铜锣湾横着走 2024-10-06 00:02:34

如果您需要事先验证电子邮件地址,请在云端硬盘中创建一个空白电子表格。然后,运行下面的函数,将 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 中验证电子邮件地址? 的正则表达式

If you need to validate email addresses beforehand, create a blank spreadsheet in your drive. Then, run the function below, changing the testSheet variable to point to the spreadsheet you created. The function will do a simple regex test to catch malformed addresses, then check if the address is actually valid by attempting to temporarily add it as a viewer on the spreadsheet. If the address can be added, it must be valid.

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;
  }
}

regex from How to validate email address in JavaScript?

飞烟轻若梦 2024-10-06 00:02:34

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

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

Stay calm, catch and log the exception and carry on:

try {
  // do stuff, including send email
  MailApp.sendEmail(email, subject, msg)
} catch(e) {
  Logger.log("Error with email (" + email + "). " + e);
}
谈情不如逗狗 2024-10-06 00:02:34

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

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());
       
    }
}

完整过程请参见此处。

On the otherhand, avoid Checking email in script and get rid of loses quota or try-catch etc. I used that I got a valid email when user attempt to send an email, by signing him in an email and got that email:

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());
       
    }
}

Full procedure Here.

一袭白衣梦中忆 2024-10-06 00:02:34

这个答案比这个问题的提出要晚得多,但我根据评论借鉴了 remitnotpaucity 的答案在他的回答中。它基本上执行相同的操作,将电子邮件添加到电子表格并捕获错误,但在我的例子中,它创建一个新的电子表格,尝试添加用户,然后在尝试添加用户后删除电子表格。在这两种情况下,无论电子邮件是否有效,它都会删除新创建的电子表格。

需要注意的一些事情:

  1. 我对正则表达式不太熟悉,所以我只检查 @ 符号是否在读入函数的电子邮件中,而不检查空格。
  2. 我相信,即使它通过了第一个 if 语句,即使它不是有效的电子邮件,仍然会抛出并捕获错误,因为 Google 仍然会发现它不是有效的电子邮件,从而使第一个 if 语句变得多余
  3. 如果您正在尝试验证您公司外部的电子邮件,我不确定它会如何反应,因此请预先警告
  4. 此验证方法需要几秒钟,因为您正在创建然后删除电子邮件全部在单个函数中,所以它比 remitnotpaucity 花费的时间要长一些。
  5. 最重要的是,如果你可以的话,我会使用 API。我相信 这个 可以完美地工作并且应该是免费的,只是可能需要一些额外的努力开始使用 GAS。
function validateEmail(email){
    let ss = SpreadsheetApp.openByUrl(SpreadsheetApp.create('Email Validation Spreadsheet', 1, 1).getUrl())
    if(!new RegExp('[@]').test(email)){
      return false
    } else{
      try{
        ss.addViewer(email)
      } catch(e){
        setTrashed()
        return false
      }
      setTrashed()
      return true
    }
    function setTrashed(){
      DriveApp.getFilesByName('Email Validation Spreadsheet').next().setTrashed(true)
    }
  }

This answer is much later than this question was asked, but I piggy-backed off of remitnotpaucity's answer based on a comment in his answer. It does basically the same thing, adding the email to the spreadsheet and catching the error, however in my case it creates a new spreadsheet, attempts to add the user, and then after attempting to add the user, deletes the spreadsheet. In both cases, that the email is a valid email or not, it deletes the newly created spreadsheet.

Some things to note:

  1. I am not as familiar with regular expressions, so I only check to see if the @ symbol is within the email read into the function, and do not check for whitespaces.
  2. I believe that even if it passes the first if-statement, even if it's not a valid email, an error will still be thrown and caught because Google will still catch that it's not a valid email, making the first if-statement redundant
  3. If you are trying to validate an email outside your company, I'm unsure how it would react, so be fore-warned about that
  4. This validation method takes a few seconds because you are creating and then deleting an email all within a single function, so it takes a fair bit longer than remitnotpaucity's
  5. Most importantly, if you are able to, I would use an API. I believe that this one would work perfectly fine and should be free, it just may take some extra elbow-grease to get to work with GAS.
function validateEmail(email){
    let ss = SpreadsheetApp.openByUrl(SpreadsheetApp.create('Email Validation Spreadsheet', 1, 1).getUrl())
    if(!new RegExp('[@]').test(email)){
      return false
    } else{
      try{
        ss.addViewer(email)
      } catch(e){
        setTrashed()
        return false
      }
      setTrashed()
      return true
    }
    function setTrashed(){
      DriveApp.getFilesByName('Email Validation Spreadsheet').next().setTrashed(true)
    }
  }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文