دمج البريد

المقدمة

يأخذ دمج البريد قيمًا من صفوف جدول بيانات أو مصدر بيانات آخر ويدرجها في مستند نموذج. يتيح لك هذا الإجراء إنشاء مستند "رئيسي" واحد (النموذج) يمكنك من خلاله إنشاء العديد من المستندات المشابهة، ويتم تخصيص كل واحد من هذه البيانات باستخدام البيانات التي يتم دمجها. ولا تُستخدم النتيجة بالضرورة لرسائل البريد أو النماذج، بل يمكن استخدامها لأي غرض على الإطلاق، مثل إنشاء مجموعة من فواتير العملاء.

لقد كانت ميزة "دمج البريد" موجودة منذ توفُّر جداول بيانات وبرامج معالجة كلمات، وهي جزء من العديد من مهام سير العمل اليوم. تتمثل الاتفاقية في تنظيم البيانات كسجل واحد في كل صف، والأعمدة التي تمثل الحقول في البيانات، كما هو موضح في الجدول التالي:

A ب C
1 الاسم العنوان المنطقة
2 UrbanPq شارع 123 المنطقة الغربية
3 باوكانا 456 الشارع الثاني المنطقة الجنوبية
4 غير ذلك.

يعرض نموذج التطبيق على هذه الصفحة كيفية استخدام واجهات برمجة التطبيقات في "مستندات Google" و"جداول بيانات Google " (وDrive) لإزالة تفاصيل كيفية إجراء عمليات دمج البريد، وحماية المستخدمين من مخاوف التنفيذ. يمكن العثور على مزيد من المعلومات حول هذه العيّنة في القائمة المفتوحة المصدر للعيّنة.

نموذج التطبيق

ينسخ نموذج التطبيق هذا النموذج الرئيسي ثم يدمج المتغيّرات من مصدر البيانات المحدّد في كل نسخة من النُسخ. لتجربة نموذج التطبيق، عليك أولاً إعداد النموذج:

  • إنشاء ملف جديد في "مستندات Google". اختَر أي نموذج تريد استخدامه. (يستخدم نموذج العيّنة Litar/Spearmint.)
  • لاحظ رقم تعريف المستند، وهو السلسلة التي تلي document/d/ (راجِع DOCUMENT_ID) في عنوان URL: https://docs.google.com/document/d/DOCUMENT_ID/edit
  • اضبط المتغيّر DOCS_FILE_ID في الرمز إلى رقم تعريف المستند هذا.
  • استبدل معلومات الاتصال في المستند بمتغيّرات العنصر النائب للنموذج التي سيتم دمجها في التطبيق مع البيانات المطلوبة.

في ما يلي نموذج لنموذج أحرف يحتوي على عناصر نائبة لدمجها مع بيانات حقيقية من مصدر مثل "جدول بيانات Google" أو نص عادي. وفي ما يلي الشكل الذي يظهر به هذا النموذج:

بعد ذلك، اختَر نصًا عاديًا أو "جداول بيانات Google" كمصدر للبيانات من خلال ضبط المتغيّر SOURCE. ويتم ضبطها تلقائيًا على النص العادي، ما يعني نموذج بيانات في المتغيّر TEXT_SOURCE_DATA. لمصدر البيانات من جدول بيانات Google، يمكنك تعديل المتغيّر SOURCE إلى 'sheets' وتوجيهه إلى نموذجنا (أو مَشاهدك من خلال ضبط المتغيّر SHEETS_FILE_ID). وإليك جدول البيانات الذي تستخدمه لتكوين فكرة عن التنسيق:

يمكنك تجربة التطبيق باستخدام نماذج البيانات، ثم التكيّف مع بياناتك وحالة الاستخدام. ويعمل تطبيق سطر الأوامر كما يلي:

  • الإعداد
  • استرجاع البيانات من مصدر البيانات
  • تكرار كل صف من البيانات
    • إنشاء نسخة من النموذج
    • دمج النسخة مع البيانات
    • رابط ناتج إلى مستند تم دمجه حديثًا

وتظهر جميع الأحرف المدمجة الجديدة أيضًا في Google Drive للمستخدم. مثال على حرف مُدمج يبدو على النحو التالي:

رمز مصدر

لغة 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 بالإضافة إلى رمز مصدر التطبيق الكامل في نموذج مفتوح المصدر الخاص بهذا التطبيق.