সেভ করা পৃষ্ঠা গুছিয়ে রাখতে 'সংগ্রহ' ব্যবহার করুন আপনার পছন্দ অনুযায়ী কন্টেন্ট সেভ করুন ও সঠিক বিভাগে রাখুন।
এই গাইডটি ব্যাখ্যা করে যে কিভাবে একটি মেল মার্জ করতে Google ডক্স API ব্যবহার করতে হয়।
ভূমিকা
একটি মেল মার্জ একটি স্প্রেডশীটের সারি বা অন্য ডেটা উত্স থেকে মান নেয় এবং সেগুলিকে একটি টেমপ্লেট নথিতে সন্নিবেশ করে। এটি আপনাকে একটি একক প্রাথমিক নথি (টেমপ্লেট) তৈরি করতে দেয় যেখান থেকে আপনি অনেকগুলি অনুরূপ নথি তৈরি করতে পারেন, প্রতিটি ডেটা একত্রিত হওয়ার সাথে কাস্টমাইজ করা হয়। ফলাফলটি অগত্যা মেল বা ফর্ম অক্ষরের জন্য ব্যবহার করা হয় না, তবে যে কোনও উদ্দেশ্যে হতে পারে, যেমন গ্রাহক চালানগুলির একটি ব্যাচ তৈরি করা।
যতদিন স্প্রেডশীট এবং ওয়ার্ড প্রসেসর রয়েছে ততদিন ধরেই মেল একত্রিত হয়েছে, এবং এটি আজ অনেক ব্যবসায়িক কর্মপ্রবাহের অংশ। কনভেনশন হল ডেটাকে প্রতি সারিতে একটি রেকর্ড হিসাবে সংগঠিত করা, কলামগুলি ডেটাতে ক্ষেত্রগুলিকে প্রতিনিধিত্ব করে, যেমনটি নিম্নলিখিত টেবিলে দেখানো হয়েছে:
নাম
ঠিকানা
জোন
1
আরবানপিকিউ
123 1ম সেন্ট।
পশ্চিম
2
পক্সানা
456 2nd St.
দক্ষিণ
এই পৃষ্ঠার নমুনা অ্যাপটি দেখায় কিভাবে আপনি Google ডক্স, শীট এবং ড্রাইভ API ব্যবহার করতে পারেন কিভাবে মেল মার্জগুলি সঞ্চালিত হয় তার বিশদ বিমূর্ত করতে, ব্যবহারকারীদের বাস্তবায়ন উদ্বেগ থেকে রক্ষা করে৷ এই পাইথন নমুনা সম্পর্কে আরও তথ্য নমুনার GitHub রেপোতে পাওয়া যাবে।
নমুনা আবেদন
এই নমুনা অ্যাপটি আপনার প্রাথমিক টেমপ্লেট অনুলিপি করে এবং তারপরে আপনার মনোনীত ডেটা উৎস থেকে ভেরিয়েবলগুলিকে প্রতিটি কপিতে মার্জ করে। এই নমুনা অ্যাপটি চেষ্টা করতে, প্রথমে আপনার টেমপ্লেট সেট আপ করুন:
নতুন ফাইলের ডকুমেন্ট আইডি নোট করুন। আরও তথ্যের জন্য, ডকুমেন্ট আইডি দেখুন।
ডকুমেন্ট আইডিতে DOCS_FILE_ID ভেরিয়েবল সেট করুন।
টেমপ্লেট প্লেসহোল্ডার ভেরিয়েবলের সাথে যোগাযোগের তথ্য প্রতিস্থাপন করুন যা অ্যাপটি নির্বাচিত ডেটার সাথে একত্রিত হবে।
এখানে স্থানধারক সহ একটি নমুনা অক্ষর টেমপ্লেট রয়েছে যা প্লেইন টেক্সট বা পত্রকের মতো উৎস থেকে প্রকৃত ডেটার সাথে মার্জ করা যেতে পারে। সেই টেমপ্লেটটি দেখতে কেমন তা এখানে:
এরপরে, SOURCE ভেরিয়েবল ব্যবহার করে আপনার ডেটা উৎস হিসেবে প্লেইন টেক্সট বা শীট বেছে নিন। নমুনাটি প্লেইন টেক্সটে ডিফল্ট হয়, যার অর্থ নমুনা ডেটা TEXT_SOURCE_DATA ভেরিয়েবল ব্যবহার করে। পত্রক থেকে ডেটা উৎস করতে, SOURCE ভেরিয়েবলটিকে 'sheets' এ আপডেট করুন এবং SHEETS_FILE_ID ভেরিয়েবল সেট করে এটিকে আমাদের নমুনা শীটে (বা আপনার নিজস্ব) নির্দেশ করুন৷
শীটটি দেখতে কেমন তা এখানে রয়েছে যাতে আপনি বিন্যাসটি দেখতে পারেন:
আমাদের নমুনা ডেটা সহ অ্যাপটি ব্যবহার করে দেখুন, তারপর এটিকে আপনার ডেটা এবং ব্যবহারের ক্ষেত্রে মানিয়ে নিন। কমান্ড লাইন অ্যাপ্লিকেশন এই মত কাজ করে:
সেটআপ
ডেটা উৎস থেকে ডেটা আনুন
ডেটার প্রতিটি সারির মাধ্যমে লুপ করুন
টেমপ্লেটের একটি অনুলিপি তৈরি করুন
ডেটার সাথে কপিটি মার্জ করুন
নতুন-একত্রিত নথিতে আউটপুট লিঙ্ক
সমস্ত নতুন মার্জ করা অক্ষরগুলি ব্যবহারকারীর আমার ড্রাইভেও দেখায়৷ একটি মার্জড অক্ষরের একটি উদাহরণ এইরকম কিছু দেখায়:
importtimeimportgoogle.authfromgoogleapiclient.discoveryimportbuildfromgoogleapiclient.errorsimportHttpError# Fill-in IDs of your Docs template & any Sheets data sourceDOCS_FILE_ID="195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE"SHEETS_FILE_ID="11pPEzi1vCMNbdpqaQx4N43rKmxvZlgEHE9GqpYoEsWw"# authorization constantsSCOPES=(# 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 constantsSOURCES=("text","sheets")SOURCE="text"# Choose one of the data SOURCESCOLUMNS=["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 variablesmerge={# 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 APIsDRIVE=build("drive","v2",credentials=creds)DOCS=build("docs","v1",credentials=creds)SHEETS=build("sheets","v4",credentials=creds)defget_data(source):"""Gets mail merge data from chosen data source."""try:ifsourcenotin{"sheets","text"}:raiseValueError(f"ERROR: unsupported source {source}; choose from {SOURCES}")returnSAFE_DISPATCH[source]()exceptHttpErroraserror:print(f"An error occurred: {error}")returnerrordef_get_text_data():"""(private) Returns plain text data; can alter to read from CSV file."""returnTEXT_SOURCE_DATAdef_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")forkinSOURCES}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"))exceptHttpErroraserror:print(f"An error occurred: {error}")returnerrordefmerge_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 valuescopy_id=_copy_template(tmpl_id,source,service)context=merge.iteritems()ifhasattr({},"iteritems")elsemerge.items()# "search & replace" API requests for mail merge substitutionsreqs=[{"replaceAllText":{"containsText":{"text":"{{%s}}"%key.upper(),# {{VARS}} are uppercase"matchCase":True,},"replaceText":value,}}forkey,valueincontext]# send requests to Docs API to do actual mergeDOCS.documents().batchUpdate(body={"requests":reqs},documentId=copy_id,fields="").execute()returncopy_idexceptHttpErroraserror:print(f"An error occurred: {error}")returnerrorif__name__=="__main__":# get row data, then loop through & process each form letterdata=get_data(SOURCE)# get data from data sourcefori,rowinenumerate(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)))
আরও তথ্যের জন্য, নমুনা অ্যাপের GitHub রেপোতেREADME ফাইল এবং সম্পূর্ণ অ্যাপ্লিকেশন সোর্স কোডটি দেখুন।
[[["সহজে বোঝা যায়","easyToUnderstand","thumb-up"],["আমার সমস্যার সমাধান হয়েছে","solvedMyProblem","thumb-up"],["অন্যান্য","otherUp","thumb-up"]],[["এতে আমার প্রয়োজনীয় তথ্য নেই","missingTheInformationINeed","thumb-down"],["খুব জটিল / অনেক ধাপ","tooComplicatedTooManySteps","thumb-down"],["পুরনো","outOfDate","thumb-down"],["অনুবাদ সংক্রান্ত সমস্যা","translationIssue","thumb-down"],["নমুনা / কোড সংক্রান্ত সমস্যা","samplesCodeIssue","thumb-down"],["অন্যান্য","otherDown","thumb-down"]],["2025-03-22 UTC-তে শেষবার আপডেট করা হয়েছে।"],[],[],null,["This guide explains how to use the Google Docs API to perform a mail merge.\n| **Note:** If you want to perform a mail merge using the Gmail web UI, see [Send personalized emails with mail\n| merge](https://support.google.com/mail/answer/12921167).\n\nIntroduction \n\nA *mail merge* takes values from rows of a spreadsheet or another data source\nand inserts them into a template document. This lets you create a single primary\ndocument (the template) from which you can generate many similar documents, each\ncustomized with the data being merged. The result isn't necessarily used for\nmail or form letters, but can be for any purpose, such as generating a batch of\ncustomer invoices.\n\nMail merge has been around for as long as there have been spreadsheets and word\nprocessors, and is part of many business workflows today. The convention is to\norganize the data as one record per row, with the columns representing fields in\nthe data, as shown in the following table:\n\n| | Name | Address | Zone |\n|---|---------|-------------|-------|\n| 1 | UrbanPq | 123 1st St. | West |\n| 2 | Pawxana | 456 2nd St. | South |\n\nThe sample app on this page shows how you can use the Google Docs,\nSheets, and Drive APIs to abstract away the\ndetails of how mail merges are performed, protecting users from implementation\nconcerns. More information on this Python sample can be found at the sample's\n[GitHub\nrepo](https://github.com/googleworkspace/python-samples/tree/main/docs/mail-merge).\n| **Note:** You must have a Google Cloud project set up so that you have credentials to make this work. More information is available in the [Python\n| quickstart](/workspace/docs/api/quickstart/python). Be sure to have the Google Drive, Docs, and Sheets APIs enabled in your project and your credentials JSON file downloaded as `credentials.json`.\n\nSample application\n\nThis sample app copies your primary template and then merges variables from your\ndesignated data source into each of the copies. To try this sample app, first\nset up your template:\n\n1. [Create a Docs file](/workspace/docs/api/how-tos/documents). Choose the template you want to use.\n2. Note the new file's document ID. For more information, see [Document\n ID](/workspace/docs/api/concepts/document#document-id).\n3. Set the `DOCS_FILE_ID` variable to the document ID.\n4. Replace the contact information with template placeholder variables that the app will merge with the selected data.\n\nHere's a [sample letter\ntemplate](https://drive.google.com/open?id=1Xycxuuv7OhEQUuzbt_Mw0TPMq02MseSD1vZdBJ3nLjk)\nwith placeholders that can be merged with real data from a source such as plain\ntext or Sheets. Here's what that template looks like:\n\n| The structure of the template variables is arbitrary. The example uses values enclosed in double braces `{{VALUE}}` because text like this is extremely unlikely to appear in document content. This style of variable placeholder naming is similar to what you'll find in most templating libraries.\n\nNext, choose either plain text or Sheets as your data source\nusing the `SOURCE` variable. The sample defaults to plain text, meaning the\nsample data uses the `TEXT_SOURCE_DATA` variable. To source data from\nSheets, update the `SOURCE` variable to `'sheets'` and point it\nto [our sample\nsheet](https://drive.google.com/open?id=18yqXLEMx6l__VAIN-Zo52pL18F3rXn0_-K6gZ-vwPcc)\n(or your own) by setting the `SHEETS_FILE_ID` variable.\n\nHere's what the sheet looks like so you can see the format:\n\nTry the app with our sample data, then adapt it to your data and use case. The\ncommand-line application works like this:\n\n- Setup\n- Fetch the data from the data source\n- Loop through each row of data\n - Create a copy of the template\n - Merge the copy with the data\n - Output link to newly-merged document\n\nAll newly merged letters also show up in the user's My Drive. An\nexample of a merged letter looks something like this:\n\n| **Note:** For documents with multiple [tabs](/workspace/docs/api/how-tos/tabs), [`ReplaceAllTextRequest`](/workspace/docs/api/reference/rest/v1/documents/request#replacealltextrequest) by default applies to all tabs. See the request documentation for more information about how to work with tabs.\n\nSource code \n\nPython \ndocs/mail-merge/docs_mail_merge.py \n[View on GitHub](https://github.com/googleworkspace/python-samples/blob/main/docs/mail-merge/docs_mail_merge.py) \n\n```python\nimport time\n\nimport google.auth\nfrom googleapiclient.discovery import build\nfrom googleapiclient.errors import HttpError\n\n# Fill-in IDs of your Docs template & any Sheets data source\nDOCS_FILE_ID = \"195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE\"\nSHEETS_FILE_ID = \"11pPEzi1vCMNbdpqaQx4N43rKmxvZlgEHE9GqpYoEsWw\"\n\n# authorization constants\n\nSCOPES = ( # iterable or space-delimited string\n \"https://www.googleapis.com/auth/drive\",\n \"https://www.googleapis.com/auth/documents\",\n \"https://www.googleapis.com/auth/spreadsheets.readonly\",\n)\n\n# application constants\nSOURCES = (\"text\", \"sheets\")\nSOURCE = \"text\" # Choose one of the data SOURCES\nCOLUMNS = [\"to_name\", \"to_title\", \"to_company\", \"to_address\"]\nTEXT_SOURCE_DATA = (\n (\n \"Ms. Lara Brown\",\n \"Googler\",\n \"Google NYC\",\n \"111 8th Ave\\nNew York, NY 10011-5201\",\n ),\n (\n \"Mr. Jeff Erson\",\n \"Googler\",\n \"Google NYC\",\n \"76 9th Ave\\nNew York, NY 10011-4962\",\n ),\n)\n\n# fill-in your data to merge into document template variables\nmerge = {\n # sender data\n \"my_name\": \"Ayme A. Coder\",\n \"my_address\": \"1600 Amphitheatre Pkwy\\nMountain View, CA 94043-1351\",\n \"my_email\": \"http://google.com\",\n \"my_phone\": \"+1-650-253-0000\",\n # - - - - - - - - - - - - - - - - - - - - - - - - - -\n # recipient data (supplied by 'text' or 'sheets' data source)\n \"to_name\": None,\n \"to_title\": None,\n \"to_company\": None,\n \"to_address\": None,\n # - - - - - - - - - - - - - - - - - - - - - - - - - -\n \"date\": time.strftime(\"%Y %B %d\"),\n # - - - - - - - - - - - - - - - - - - - - - - - - - -\n \"body\": (\n \"Google, headquartered in Mountain View, unveiled the new \"\n \"Android phone at the Consumer Electronics Show. CEO Sundar \"\n \"Pichai said in his keynote that users love their new phones.\"\n ),\n}\n\ncreds, _ = google.auth.default()\n# pylint: disable=maybe-no-member\n\n# service endpoints to Google APIs\n\nDRIVE = build(\"drive\", \"v2\", credentials=creds)\nDOCS = build(\"docs\", \"v1\", credentials=creds)\nSHEETS = build(\"sheets\", \"v4\", credentials=creds)\n\n\ndef get_data(source):\n \"\"\"Gets mail merge data from chosen data source.\"\"\"\n try:\n if source not in {\"sheets\", \"text\"}:\n raise ValueError(\n f\"ERROR: unsupported source {source}; choose from {SOURCES}\"\n )\n return SAFE_DISPATCH[source]()\n except HttpError as error:\n print(f\"An error occurred: {error}\")\n return error\n\n\ndef _get_text_data():\n \"\"\"(private) Returns plain text data; can alter to read from CSV file.\"\"\"\n return TEXT_SOURCE_DATA\n\n\ndef _get_sheets_data(service=SHEETS):\n \"\"\"(private) Returns data from Google Sheets source. It gets all rows of\n 'Sheet1' (the default Sheet in a new spreadsheet), but drops the first\n (header) row. Use any desired data range (in standard A1 notation).\n \"\"\"\n return (\n service.spreadsheets()\n .values()\n .get(spreadsheetId=SHEETS_FILE_ID, range=\"Sheet1\")\n .execute()\n .get(\"values\")[1:]\n )\n # skip header row\n\n\n# data source dispatch table [better alternative vs. eval()]\nSAFE_DISPATCH = {k: globals().get(f\"_get_{k}_data\") for k in SOURCES}\n\n\ndef _copy_template(tmpl_id, source, service):\n \"\"\"(private) Copies letter template document using Drive API then\n returns file ID of (new) copy.\n \"\"\"\n try:\n body = {\"name\": f\"Merged form letter ({source})\"}\n return (\n service.files()\n .copy(body=body, fileId=tmpl_id, fields=\"id\")\n .execute()\n .get(\"id\")\n )\n except HttpError as error:\n print(f\"An error occurred: {error}\")\n return error\n\n\ndef merge_template(tmpl_id, source, service):\n \"\"\"Copies template document and merges data into newly-minted copy then\n returns its file ID.\n \"\"\"\n try:\n # copy template and set context data struct for merging template values\n copy_id = _copy_template(tmpl_id, source, service)\n context = merge.iteritems() if hasattr({}, \"iteritems\") else merge.items()\n\n # \"search & replace\" API requests for mail merge substitutions\n reqs = [\n {\n \"replaceAllText\": {\n \"containsText\": {\n \"text\": \"{{%s}}\" % key.upper(), # {{VARS}} are uppercase\n \"matchCase\": True,\n },\n \"replaceText\": value,\n }\n }\n for key, value in context\n ]\n\n # send requests to Docs API to do actual merge\n DOCS.documents().batchUpdate(\n body={\"requests\": reqs}, documentId=copy_id, fields=\"\"\n ).execute()\n return copy_id\n except HttpError as error:\n print(f\"An error occurred: {error}\")\n return error\n\n\nif __name__ == \"__main__\":\n # get row data, then loop through & process each form letter\n data = get_data(SOURCE) # get data from data source\n for i, row in enumerate(data):\n merge.update(dict(zip(COLUMNS, row)))\n print(\n \"Merged letter %d: docs.google.com/document/d/%s/edit\"\n % (i + 1, merge_template(DOCS_FILE_ID, SOURCE, DRIVE))\n )\n```\n\nFor more information, see the `README` file and the full application source code\nat the sample app's [GitHub\nrepo](https://github.com/googleworkspace/python-samples/tree/main/docs/mail-merge).\n\nRelated topics\n\n- [Send personalized emails with mail merge](https://support.google.com/mail/answer/12921167)\n- [Create a mail merge with Gmail \\& Google Sheets](/apps-script/samples/automations/mail-merge)"]]