Kreator e-maili za pomocą interfejsu API Dokumentów
Zadbaj o dobrą organizację dzięki kolekcji Zapisuj i kategoryzuj treści zgodnie ze swoimi preferencjami.
Z tego przewodnika dowiesz się, jak użyć interfejsu Google Docs API do wykonania scalania wiadomości e-mail.
Wprowadzenie
Zbiorcze wiadomości pobierają wartości z wierszy arkusza kalkulacyjnego lub innego źródła danych i wstawiają je do dokumentu szablonu. Dzięki temu możesz utworzyć jeden główny dokument (szablon), na podstawie którego możesz wygenerować wiele podobnych dokumentów, z których każdy będzie dostosowany do danych, które mają być scalone. Wynik nie musi być używany do wysyłania e-maili ani listów, ale może służyć do dowolnego celu, np. do generowania partii faktur dla klientów.
Korespondencja zbiorcza istnieje od czasów, gdy pojawiły się arkusze kalkulacyjne i edytory tekstu, i jest obecnie częścią wielu procesów biznesowych. Zgodnie z konwencją dane są uporządkowane w taki sposób, że każdy wiersz zawiera 1 rekord, a kolumny reprezentują pola danych, jak pokazano w tabeli poniżej:
Nazwa
Adres
Strefa
1
UrbanPq
123 ul. Pierwsza
zachód
2
Pawxana
456 2nd St.
południe
Przykładowa aplikacja na tej stronie pokazuje, jak można używać interfejsów Google Docs, Arkuszy i Dysku, aby ukryć szczegóły dotyczące tego, jak odbywa się scalanie wiadomości e-mail, i chronić użytkowników przed problemami związanymi z implementacją. Więcej informacji o tym przykładzie kodu Pythona znajdziesz w repozytorium GitHub.
Przykładowa aplikacja
Ta przykładowa aplikacja kopiuje główny szablon, a następnie scala zmienne z wybranego źródła danych z każdą z kopii. Aby wypróbować tę przykładową aplikację, najpierw skonfiguruj szablon:
Zanotuj identyfikator dokumentu nowego pliku. Więcej informacji znajdziesz w sekcji Identyfikator dokumentu.
Ustaw zmienną DOCS_FILE_ID na identyfikator dokumentu.
Zastąp informacje o kontakcie zmiennymi zastępczymi szablonu, które aplikacja scali z wybranymi danymi.
Oto szablon przykładowego listu z obiektami zastępczymi, które można scalić z rzeczywistymi danymi ze źródła, takiego jak zwykły tekst lub Arkusze. Oto jak wygląda ten szablon:
Następnie za pomocą zmiennej SOURCE wybierz zwykły tekst lub Arkusze jako źródło danych. Domyślnie jest to zwykły tekst, co oznacza, że dane przykładowe używają zmiennej TEXT_SOURCE_DATA. Aby pobrać dane z Arkuszy, zmień zmienną SOURCE na 'sheets' i skieruj ją do naszego przykładowego arkusza (lub własnego), ustawiając zmienną SHEETS_FILE_ID.
Oto jak wygląda arkusz, aby można było zobaczyć format:
Wypróbuj aplikację z naszych przykładowych danych, a potem dostosuj ją do swoich danych i przypadku użycia. Aplikacja wiersza poleceń działa w ten sposób:
Konfiguracja
Pobieranie danych ze źródła danych
Przechodzenie przez poszczególne wiersze danych
Utwórz kopię szablonu
Połącz kopię z danymi
Link wyjściowy do nowo scalonego dokumentu
Wszystkie nowo scalone listy pojawiają się też na Moim dysku użytkownika. Przykład scalonego dokumentu:
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)))
Więcej informacji znajdziesz w pliku README i pełnym kodzie źródłowym aplikacji w repozytorium GitHub przykładowej aplikacji.
[[["Łatwo zrozumieć","easyToUnderstand","thumb-up"],["Rozwiązało to mój problem","solvedMyProblem","thumb-up"],["Inne","otherUp","thumb-up"]],[["Brak potrzebnych mi informacji","missingTheInformationINeed","thumb-down"],["Zbyt skomplikowane / zbyt wiele czynności do wykonania","tooComplicatedTooManySteps","thumb-down"],["Nieaktualne treści","outOfDate","thumb-down"],["Problem z tłumaczeniem","translationIssue","thumb-down"],["Problem z przykładami/kodem","samplesCodeIssue","thumb-down"],["Inne","otherDown","thumb-down"]],["Ostatnia aktualizacja: 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)"]]