Apps Script 快速入門導覽課程

本文說明如何使用 Apps Script 傳送含有結構化資料的電子郵件給自己,藉此測試電子郵件標記。

建立專案

前往 script.google.com。如果您是第一次前往 script.google.com,系統會將您重新導向至資訊頁面。按一下「Start Scripting」(開始編寫指令碼),前往指令碼編輯器。在指令碼編輯器中,為「空白專案」建立指令碼。

Code.gs 中的程式碼替換為下列程式碼:

gmail/markup/Code.gs
/**
 * Send an email with schemas in order to test email markup.
 */
function testSchemas() {
  try {
    const htmlBody = HtmlService.createHtmlOutputFromFile('mail_template').getContent();

    MailApp.sendEmail({
      to: Session.getActiveUser().getEmail(),
      subject: 'Test Email markup - ' + new Date(),
      htmlBody: htmlBody
    });
  } catch (err) {
    console.log(err.message);
  }
}

依序選取「File」>「New」>「Html file」,即可建立新的 HTML 檔案。將檔案命名為 mail_template,與上述 JavaScript 中的參數相符。將 HTML 檔案內容替換成下列內容:

gmail/markup/mail_template.html
<!--
 Copyright 2022 Google LLC

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-->

<html>
  <head>
    <script type="application/ld+json">
    {
      "@context": "https://schema.org",
      "@type": "EmailMessage",
      "description": "Check this out",
      "potentialAction": {
        "@type": "ViewAction",
        "target": "https://www.youtube.com/watch?v=eH8KwfdkSqU"
      }
    }
    </script>
  </head>
  <body>
    <p>
      This a test for a Go-To action in Gmail.
    </p>
  </body>
</html>

測試指令碼

如要測試指令碼,請執行下列操作:

  1. 儲存專案。
  2. 選取「Code.gs」分頁。
  3. 確認已在 Select function 下拉式選單中選取 testSchemas 函式。
  4. 在 Apps Script 開發環境中按一下 Run

第一次執行指令碼時,系統會要求您授予授權,之後請重新執行指令碼。指令碼執行完畢後,請檢查收件匣中是否有自己寄出的電子郵件,內含「前往動作」按鈕,如下列螢幕截圖所示:

Apps Script 教學課程

指令碼的運作方式

testSchemas 函式會從名為 mail_template.html 的檔案讀取 HTML 內容,並以電子郵件的形式將該內容傳送給目前已通過驗證的使用者。如「向 Google 註冊」一文所述,您傳送給自己的所有結構化資料都會顯示在 Gmail 中,因此您可以使用指令碼傳送的電子郵件,在測試時忽略註冊規定。