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

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

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

ไปที่ 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 ให้ตรงกับพารามิเตอร์ใน 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 Script

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

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