Apps 脚本快速入门

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

创建项目

访问 script.google.com。如果这是您首次访问script.google.com,系统会将您重定向至信息页面。点击开始编写脚本以转到脚本编辑器。在脚本编辑器中,为 Blank Project 创建一个脚本。

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,以匹配上述 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 中,因此该脚本发送的电子邮件可用于忽略注册要求,以便进行测试。