การผสานอีเมลกับ API เอกสาร

คู่มือนี้จะอธิบายวิธีใช้ Google เอกสาร API เพื่อผสานอีเมล

บทนำ

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

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

ชื่อ ที่อยู่ โซน
1 UrbanPq 123 สตรีต 1 ตะวันตก
2 พาวซานา 456 ถนน 2 ใต้

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

แอปพลิเคชันตัวอย่าง

แอปตัวอย่างนี้คัดลอกเทมเพลตหลัก แล้วผสานตัวแปรจาก ข้อมูลที่กำหนดลงในสำเนาแต่ละชุด หากต้องการลองใช้แอปตัวอย่างนี้ ก่อนอื่นให้ ตั้งค่าเทมเพลต

  1. สร้างไฟล์เอกสาร เลือก เทมเพลตที่ต้องการใช้
  2. จดรหัสเอกสารของไฟล์ใหม่ สำหรับข้อมูลเพิ่มเติม โปรดดูที่เอกสาร รหัส
  3. ตั้งค่าตัวแปร DOCS_FILE_ID เป็นรหัสเอกสาร
  4. แทนที่ข้อมูลติดต่อด้วยตัวแปรตัวยึดตําแหน่งเทมเพลตที่ แอปจะรวมเข้ากับข้อมูลที่เลือก

โปรดดูจดหมายตัวอย่าง เทมเพลต ด้วยตัวยึดตำแหน่งที่สามารถผสานกับข้อมูลจริงจากแหล่งที่มา เช่น ข้อความธรรมดา ข้อความหรือชีต เทมเพลตจะมีลักษณะดังนี้

ถัดไป ให้เลือกข้อความธรรมดาหรือชีตเป็นแหล่งข้อมูล โดยใช้ตัวแปร SOURCE ตัวอย่างมีค่าเริ่มต้นเป็นข้อความธรรมดา ซึ่งหมายความว่า ข้อมูลตัวอย่างใช้ตัวแปร TEXT_SOURCE_DATA เป็นแหล่งข้อมูลจาก ชีต ให้อัปเดตตัวแปร SOURCE เป็น 'sheets' แล้วชี้ ไปยังตัวอย่างของเรา ชีต (หรือของคุณเอง) โดยการตั้งค่าตัวแปร SHEETS_FILE_ID

ต่อไปนี้คือลักษณะของชีตเพื่อให้คุณเห็นรูปแบบ

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

  • ตั้งค่า
  • ดึงข้อมูลจากแหล่งข้อมูล
  • วนซ้ำข้อมูลแต่ละแถว
    • สร้างสำเนาของเทมเพลต
    • ผสานสำเนากับข้อมูล
    • ลิงก์เอาต์พุตไปยังเอกสารที่รวมใหม่

ตัวอักษรที่รวมเข้าด้วยกันใหม่ทั้งหมดจะปรากฏใน "ไดรฟ์ของฉัน" ของผู้ใช้ CANNOT TRANSLATE ตัวอย่างของตัวอักษรที่รวมเข้าด้วยกันมีลักษณะดังนี้

ซอร์สโค้ด

Python

docs/mail-merge/docs_mail_merge.py
import time

import google.auth
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError

# Fill-in IDs of your Docs template & any Sheets data source
DOCS_FILE_ID = "195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE"
SHEETS_FILE_ID = "11pPEzi1vCMNbdpqaQx4N43rKmxvZlgEHE9GqpYoEsWw"

# authorization constants

SCOPES = (  # iterable or space-delimited string
    "https://www.googleapis.com/auth/drive",
    "https://www.googleapis.com/auth/documents",
    "https://www.googleapis.com/auth/spreadsheets.readonly",
)

# application constants
SOURCES = ("text", "sheets")
SOURCE = "text"  # Choose one of the data SOURCES
COLUMNS = ["to_name", "to_title", "to_company", "to_address"]
TEXT_SOURCE_DATA = (
    (
        "Ms. Lara Brown",
        "Googler",
        "Google NYC",
        "111 8th Ave\nNew York, NY  10011-5201",
    ),
    (
        "Mr. Jeff Erson",
        "Googler",
        "Google NYC",
        "76 9th Ave\nNew York, NY  10011-4962",
    ),
)

# fill-in your data to merge into document template variables
merge = {
    # sender data
    "my_name": "Ayme A. Coder",
    "my_address": "1600 Amphitheatre Pkwy\nMountain View, CA  94043-1351",
    "my_email": "http://google.com",
    "my_phone": "+1-650-253-0000",
    # - - - - - - - - - - - - - - - - - - - - - - - - - -
    # recipient data (supplied by 'text' or 'sheets' data source)
    "to_name": None,
    "to_title": None,
    "to_company": None,
    "to_address": None,
    # - - - - - - - - - - - - - - - - - - - - - - - - - -
    "date": time.strftime("%Y %B %d"),
    # - - - - - - - - - - - - - - - - - - - - - - - - - -
    "body": (
        "Google, headquartered in Mountain View, unveiled the new "
        "Android phone at the Consumer Electronics Show. CEO Sundar "
        "Pichai said in his keynote that users love their new phones."
    ),
}

creds, _ = google.auth.default()
# pylint: disable=maybe-no-member

# service endpoints to Google APIs

DRIVE = build("drive", "v2", credentials=creds)
DOCS = build("docs", "v1", credentials=creds)
SHEETS = build("sheets", "v4", credentials=creds)


def get_data(source):
  """Gets mail merge data from chosen data source."""
  try:
    if source not in {"sheets", "text"}:
      raise ValueError(
          f"ERROR: unsupported source {source}; choose from {SOURCES}"
      )
    return SAFE_DISPATCH[source]()
  except HttpError as error:
    print(f"An error occurred: {error}")
    return error


def _get_text_data():
  """(private) Returns plain text data; can alter to read from CSV file."""
  return TEXT_SOURCE_DATA


def _get_sheets_data(service=SHEETS):
  """(private) Returns data from Google Sheets source. It gets all rows of
  'Sheet1' (the default Sheet in a new spreadsheet), but drops the first
  (header) row. Use any desired data range (in standard A1 notation).
  """
  return (
      service.spreadsheets()
      .values()
      .get(spreadsheetId=SHEETS_FILE_ID, range="Sheet1")
      .execute()
      .get("values")[1:]
  )
  # skip header row


# data source dispatch table [better alternative vs. eval()]
SAFE_DISPATCH = {k: globals().get(f"_get_{k}_data") for k in SOURCES}


def _copy_template(tmpl_id, source, service):
  """(private) Copies letter template document using Drive API then
  returns file ID of (new) copy.
  """
  try:
    body = {"name": f"Merged form letter ({source})"}
    return (
        service.files()
        .copy(body=body, fileId=tmpl_id, fields="id")
        .execute()
        .get("id")
    )
  except HttpError as error:
    print(f"An error occurred: {error}")
    return error


def merge_template(tmpl_id, source, service):
  """Copies template document and merges data into newly-minted copy then
  returns its file ID.
  """
  try:
    # copy template and set context data struct for merging template values
    copy_id = _copy_template(tmpl_id, source, service)
    context = merge.iteritems() if hasattr({}, "iteritems") else merge.items()

    # "search & replace" API requests for mail merge substitutions
    reqs = [
        {
            "replaceAllText": {
                "containsText": {
                    "text": "{{%s}}" % key.upper(),  # {{VARS}} are uppercase
                    "matchCase": True,
                },
                "replaceText": value,
            }
        }
        for key, value in context
    ]

    # send requests to Docs API to do actual merge
    DOCS.documents().batchUpdate(
        body={"requests": reqs}, documentId=copy_id, fields=""
    ).execute()
    return copy_id
  except HttpError as error:
    print(f"An error occurred: {error}")
    return error


if __name__ == "__main__":
  # get row data, then loop through & process each form letter
  data = get_data(SOURCE)  # get data from data source
  for i, row in enumerate(data):
    merge.update(dict(zip(COLUMNS, row)))
    print(
        "Merged letter %d: docs.google.com/document/d/%s/edit"
        % (i + 1, merge_template(DOCS_FILE_ID, SOURCE, DRIVE))
    )

ดูข้อมูลเพิ่มเติมได้ที่ไฟล์ README และซอร์สโค้ดของแอปพลิเคชันฉบับเต็ม ที่ GitHub ของแอปตัวอย่าง ที่เก็บ