Apps 脚本快速入门

本文介绍如何使用 Apps 脚本向自己发送包含架构的电子邮件,以测试电子邮件标记。

创建项目

访问 script.google.com。如果这是您首次访问 script.google.com,系统会将您重定向到信息页。点击开始脚本,继续运行脚本编辑器。在脚本编辑器中,为空白项目创建脚本。

Code.gs 中的代码替换为以下代码:

Gmail/标记/代码.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);
  }
}

依次选择文件 > 新建 > HTML 文件,以创建新的 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 脚本开发环境中点击 Run

首次运行脚本时,系统会要求您授权,之后您需要重新运行该脚本。脚本运行后,查看您的收件箱中是否有自己通过 Go-To Action 按钮发送的电子邮件,如以下屏幕截图所示:

Apps 脚本教程

脚本如何工作?

testSchemas 函数从名为 mail_template.html 的文件中读取 HTML 内容,并将该内容作为电子邮件发送给当前经过身份验证的用户。如向 Google 注册中所述,您发送给自己的所有架构都将在 Gmail 中显示,因此脚本发送的电子邮件可用于忽略注册要求以进行测试。