Google Apps 脚本快速入门

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

创建项目

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

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

选择文件 > 新建 > HTML 文件以创建 HTML 文件。将文件命名为 mail_template,以与上述脚本中的参数保持一致。将 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. 确保在选择函数菜单中选择了函数 testSchemas
  4. 在 Apps 脚本开发环境中,点击运行

首次运行脚本时,系统会要求您授予授权。授权后,再次运行脚本。脚本运行后,检查您的收件箱,看看是否收到一封自己发给自己的电子邮件,其中包含一个前往操作按钮,如以下屏幕截图所示:

Apps 脚本教程

脚本如何工作?

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