簡體   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