คู่มือเริ่มใช้งาน Apps Script ฉบับย่อ

บทความนี้แสดงวิธีใช้ Apps Script เพื่อส่งอีเมลถึงตัวเองพร้อมสคีมาเพื่อทดสอบมาร์กอัปอีเมล

กำลังสร้างโปรเจ็กต์

ไปที่ script.google.com หากคุณมาที่ script.google.com เป็นครั้งแรก ระบบจะนำคุณไปยังหน้าข้อมูล คลิกเริ่มการเขียนสคริปต์เพื่อไปยังเครื่องมือแก้ไขสคริปต์ ในเครื่องมือแก้ไขสคริปต์ ให้สร้างสคริปต์สำหรับโครงการเปล่า

แทนที่โค้ดใน Code.gs ด้วยโค้ดต่อไปนี้

gmail/มาร์กอัป/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. ตรวจสอบว่าได้เลือกฟังก์ชัน testSchemas ในเมนูแบบเลื่อนลง Select function แล้ว
  4. คลิก Run ในสภาพแวดล้อมการพัฒนา Apps Script

ครั้งแรกที่คุณเรียกใช้สคริปต์ ระบบจะขอให้คุณให้สิทธิ์ หลังจากนั้นคุณควรเรียกใช้สคริปต์อีกครั้ง หลังจากสคริปต์ทำงานแล้ว ให้ตรวจสอบกล่องจดหมายเพื่อหาอีเมลที่ส่งจากคุณที่มีปุ่มไปที่การดำเนินการ ตามที่แสดงในภาพหน้าจอต่อไปนี้

บทแนะนำสคริปต์ Apps

สคริปต์ทำงานอย่างไร

ฟังก์ชัน testSchemas จะอ่านเนื้อหา HTML จากไฟล์ชื่อ mail_template.html และส่งเนื้อหานั้นเป็นอีเมลไปยังผู้ใช้ที่ตรวจสอบสิทธิ์แล้วในปัจจุบัน ตามที่อธิบายไว้ในส่วนการลงทะเบียนกับ Google สคีมาทั้งหมดที่คุณส่งให้ตัวเองจะแสดงใน Gmail ดังนั้นจึงสามารถใช้อีเมลที่ส่งโดยสคริปต์โดยไม่สนใจข้อกำหนดในการลงทะเบียนเพื่อวัตถุประสงค์ในการทดสอบ