Gmail 및 Google Sheets와 메일 병합 만들기

코딩 수준: 초급
시간: 10분
프로젝트 유형: 맞춤 메뉴를 사용한 자동화

동영상을 통해 배우고 싶으신가요?
Google Workspace 개발자 채널에서는 도움말, 유용한 정보, 최신 기능에 대한 동영상을 제공합니다.

목표

  • 솔루션의 기능을 이해합니다.
  • 솔루션 내에서 Apps Script 서비스가 하는 작업을 이해합니다.
  • 스크립트를 설정합니다.
  • 스크립트를 실행합니다.

이 솔루션 정보

이메일 템플릿을 Google Sheets의 데이터로 자동으로 채웁니다. 수신자 답장에 응답할 수 있도록 Gmail 계정에서 이메일이 전송됩니다.

중요: 이 메일 병합 샘플에는 Google 서비스 할당량에 설명된 이메일 한도가 적용됩니다.

메일 병합 예

사용 방법

Sheets 스프레드시트의 데이터에 해당하는 자리표시자를 사용하여 Gmail 초안 템플릿을 만듭니다. 시트의 각 열 헤더는 자리표시자 태그를 나타냅니다. 스크립트는 각 자리표시자의 정보를 스프레드시트에서 이메일 초안의 해당 자리표시자 태그 위치로 전송합니다.

Apps Script 서비스

이 솔루션은 다음 서비스를 사용합니다.

기본 요건

이 샘플을 사용하려면 다음과 같은 기본 요건이 필요합니다.

  • Google 계정 (Google Workspace 계정은 관리자 승인이 필요할 수 있음)
  • 인터넷에 액세스할 수 있는 웹브라우저

스크립트 설정

Apps Script 프로젝트 만들기

  1. 다음 버튼을 클릭하여 Gmail/Sheets 메일 병합 샘플 스프레드시트의 사본을 만듭니다. 이 솔루션의 Apps Script 프로젝트는 스프레드시트에 첨부되어 있습니다.
    사본 만들기
  2. 복사된 스프레드시트에서 메일 병합에 사용할 이메일 주소로 수신자 열을 업데이트합니다.
  3. (선택사항) 열을 추가, 수정 또는 삭제하여 이메일 템플릿에 포함할 데이터를 맞춤설정합니다.

Recipient 또는 Email Sent 열의 이름을 변경하는 경우 Apps Script 프로젝트에서 해당하는 코드를 업데이트해야 합니다. 확장 프로그램 > Apps Script를 클릭하여 스프레드시트에서 Apps Script 프로젝트를 열 수 있습니다.

이메일 템플릿 만들기

  1. Gmail 계정에서 이메일 초안을 만듭니다. 스프레드시트의 데이터를 이메일에 포함하려면 {{First name}}와 같이 중괄호로 묶인 열 이름에 해당하는 자리표시자를 사용하세요.
    • 이메일의 텍스트에 서식을 지정하는 경우 자리표시자 괄호의 형식도 지정해야 합니다.
    • 자리표시자는 대소문자를 구분하며 열 헤더와 정확하게 일치해야 합니다.
  2. 이메일 초안의 제목을 복사합니다.

스크립트 실행

  1. 스프레드시트에서 메일 병합 > 이메일 보내기를 클릭합니다. 이 맞춤 메뉴를 표시하려면 페이지를 새로고침해야 할 수 있습니다.
  2. 메시지가 표시되면 스크립트를 승인합니다. OAuth 동의 화면에 이 앱이 확인되지 않았습니다라는 경고가 표시되면 고급 > {프로젝트 이름}으로 이동(안전하지 않음)을 선택하여 계속 진행합니다.

  3. 메일 병합 > 이메일 보내기를 다시 클릭합니다.

  4. 이메일 템플릿 제목을 붙여넣고 확인을 클릭합니다.

시트에 필터를 적용한 경우 스크립트가 필터링된 참여자에게 이메일을 계속 보내지만 타임스탬프를 추가하지는 않습니다.

코드 검토

이 솔루션의 Apps Script 코드를 검토하려면 아래의 소스 코드 보기를 클릭하세요.

소스 코드 보기

Code.gs

solutions/automations/mail-merge/Code.js
// To learn how to use this script, refer to the documentation:
// https://developers.google.com/apps-script/samples/automations/mail-merge

/*
Copyright 2022 Martin Hawksey

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

    https://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.
*/

/**
 * @OnlyCurrentDoc
*/

/**
 * Change these to match the column names you are using for email 
 * recipient addresses and email sent column.
*/
const RECIPIENT_COL  = "Recipient";
const EMAIL_SENT_COL = "Email Sent";

/** 
 * Creates the menu item "Mail Merge" for user to run scripts on drop-down.
 */
function onOpen() {
  const ui = SpreadsheetApp.getUi();
  ui.createMenu('Mail Merge')
      .addItem('Send Emails', 'sendEmails')
      .addToUi();
}

/**
 * Sends emails from sheet data.
 * @param {string} subjectLine (optional) for the email draft message
 * @param {Sheet} sheet to read data from
*/
function sendEmails(subjectLine, sheet=SpreadsheetApp.getActiveSheet()) {
  // option to skip browser prompt if you want to use this code in other projects
  if (!subjectLine){
    subjectLine = Browser.inputBox("Mail Merge", 
                                      "Type or copy/paste the subject line of the Gmail " +
                                      "draft message you would like to mail merge with:",
                                      Browser.Buttons.OK_CANCEL);

    if (subjectLine === "cancel" || subjectLine == ""){ 
    // If no subject line, finishes up
    return;
    }
  }

  // Gets the draft Gmail message to use as a template
  const emailTemplate = getGmailTemplateFromDrafts_(subjectLine);

  // Gets the data from the passed sheet
  const dataRange = sheet.getDataRange();
  // Fetches displayed values for each row in the Range HT Andrew Roberts 
  // https://mashe.hawksey.info/2020/04/a-bulk-email-mail-merge-with-gmail-and-google-sheets-solution-evolution-using-v8/#comment-187490
  // @see https://developers.google.com/apps-script/reference/spreadsheet/range#getdisplayvalues
  const data = dataRange.getDisplayValues();

  // Assumes row 1 contains our column headings
  const heads = data.shift(); 

  // Gets the index of the column named 'Email Status' (Assumes header names are unique)
  // @see http://ramblings.mcpher.com/Home/excelquirks/gooscript/arrayfunctions
  const emailSentColIdx = heads.indexOf(EMAIL_SENT_COL);

  // Converts 2d array into an object array
  // See https://stackoverflow.com/a/22917499/1027723
  // For a pretty version, see https://mashe.hawksey.info/?p=17869/#comment-184945
  const obj = data.map(r => (heads.reduce((o, k, i) => (o[k] = r[i] || '', o), {})));

  // Creates an array to record sent emails
  const out = [];

  // Loops through all the rows of data
  obj.forEach(function(row, rowIdx){
    // Only sends emails if email_sent cell is blank and not hidden by a filter
    if (row[EMAIL_SENT_COL] == ''){
      try {
        const msgObj = fillInTemplateFromObject_(emailTemplate.message, row);

        // See https://developers.google.com/apps-script/reference/gmail/gmail-app#sendEmail(String,String,String,Object)
        // If you need to send emails with unicode/emoji characters change GmailApp for MailApp
        // Uncomment advanced parameters as needed (see docs for limitations)
        GmailApp.sendEmail(row[RECIPIENT_COL], msgObj.subject, msgObj.text, {
          htmlBody: msgObj.html,
          // bcc: 'a.bcc@email.com',
          // cc: 'a.cc@email.com',
          // from: 'an.alias@email.com',
          // name: 'name of the sender',
          // replyTo: 'a.reply@email.com',
          // noReply: true, // if the email should be sent from a generic no-reply email address (not available to gmail.com users)
          attachments: emailTemplate.attachments,
          inlineImages: emailTemplate.inlineImages
        });
        // Edits cell to record email sent date
        out.push([new Date()]);
      } catch(e) {
        // modify cell to record error
        out.push([e.message]);
      }
    } else {
      out.push([row[EMAIL_SENT_COL]]);
    }
  });

  // Updates the sheet with new data
  sheet.getRange(2, emailSentColIdx+1, out.length).setValues(out);

  /**
   * Get a Gmail draft message by matching the subject line.
   * @param {string} subject_line to search for draft message
   * @return {object} containing the subject, plain and html message body and attachments
  */
  function getGmailTemplateFromDrafts_(subject_line){
    try {
      // get drafts
      const drafts = GmailApp.getDrafts();
      // filter the drafts that match subject line
      const draft = drafts.filter(subjectFilter_(subject_line))[0];
      // get the message object
      const msg = draft.getMessage();

      // Handles inline images and attachments so they can be included in the merge
      // Based on https://stackoverflow.com/a/65813881/1027723
      // Gets all attachments and inline image attachments
      const allInlineImages = draft.getMessage().getAttachments({includeInlineImages: true,includeAttachments:false});
      const attachments = draft.getMessage().getAttachments({includeInlineImages: false});
      const htmlBody = msg.getBody(); 

      // Creates an inline image object with the image name as key 
      // (can't rely on image index as array based on insert order)
      const img_obj = allInlineImages.reduce((obj, i) => (obj[i.getName()] = i, obj) ,{});

      //Regexp searches for all img string positions with cid
      const imgexp = RegExp('<img.*?src="cid:(.*?)".*?alt="(.*?)"[^\>]+>', 'g');
      const matches = [...htmlBody.matchAll(imgexp)];

      //Initiates the allInlineImages object
      const inlineImagesObj = {};
      // built an inlineImagesObj from inline image matches
      matches.forEach(match => inlineImagesObj[match[1]] = img_obj[match[2]]);

      return {message: {subject: subject_line, text: msg.getPlainBody(), html:htmlBody}, 
              attachments: attachments, inlineImages: inlineImagesObj };
    } catch(e) {
      throw new Error("Oops - can't find Gmail draft");
    }

    /**
     * Filter draft objects with the matching subject linemessage by matching the subject line.
     * @param {string} subject_line to search for draft message
     * @return {object} GmailDraft object
    */
    function subjectFilter_(subject_line){
      return function(element) {
        if (element.getMessage().getSubject() === subject_line) {
          return element;
        }
      }
    }
  }

  /**
   * Fill template string with data object
   * @see https://stackoverflow.com/a/378000/1027723
   * @param {string} template string containing {{}} markers which are replaced with data
   * @param {object} data object used to replace {{}} markers
   * @return {object} message replaced with data
  */
  function fillInTemplateFromObject_(template, data) {
    // We have two templates one for plain text and the html body
    // Stringifing the object means we can do a global replace
    let template_string = JSON.stringify(template);

    // Token replacement
    template_string = template_string.replace(/{{[^{}]+}}/g, key => {
      return escapeData_(data[key.replace(/[{}]+/g, "")] || "");
    });
    return  JSON.parse(template_string);
  }

  /**
   * Escape cell data to make JSON safe
   * @see https://stackoverflow.com/a/9204218/1027723
   * @param {string} str to escape JSON special characters from
   * @return {string} escaped string
  */
  function escapeData_(str) {
    return str
      .replace(/[\\]/g, '\\\\')
      .replace(/[\"]/g, '\\\"')
      .replace(/[\/]/g, '\\/')
      .replace(/[\b]/g, '\\b')
      .replace(/[\f]/g, '\\f')
      .replace(/[\n]/g, '\\n')
      .replace(/[\r]/g, '\\r')
      .replace(/[\t]/g, '\\t');
  };
}

수정

필요에 따라 원하는 만큼 메일 병합 자동화를 수정할 수 있습니다. 다음은 소스 코드에서 변경할 수 있는 몇 가지 선택적 변경입니다.

숨은참조, 참조, 답장 또는 보낸사람 이메일 매개변수 추가

샘플 코드에는 현재 주석 처리된 추가 매개변수가 다수 포함되어 있습니다. 이 매개변수를 사용하면 이메일을 보내는 계정의 이름, 이메일 답장, 숨은참조 및 참조 이메일 주소를 제어할 수 있습니다.

각 매개변수 앞에 있는 슬래시(//)를 삭제하여 추가할 매개변수를 활성화합니다.

다음 샘플은 대부분의 이메일 매개변수를 활성화하는 sendEmails 함수의 발췌 부분을 보여줍니다.

GmailApp.sendEmail(row[RECIPIENT_COL], msgObj.subject, msgObj.text, {
         htmlBody: msgObj.html,
         bcc: 'bcc@example.com',
         cc: 'cc@example.com',
         from: 'from.alias@example.com',
         name: 'name of the sender',
         replyTo: 'reply@example.com',
        // noReply: true, // if the email should be sent from a generic no-reply email address (not available to gmail.com users)

위 샘플에서는 replyTo 매개변수가 설정되었으므로 noReply 매개변수가 여전히 주석 처리되어 있습니다.

이메일에 유니코드 문자를 포함하세요.

이메일에 그림 이모티콘과 같은 유니코드 문자를 포함하려면 Gmail 서비스 대신 메일 서비스를 사용하도록 코드를 업데이트해야 합니다.

샘플 코드에서 다음 줄을 업데이트합니다.

GmailApp.sendEmail(row[RECIPIENT_COL], msgObj.subject, msgObj.text, {

줄을 다음 코드로 바꿉니다.

MailApp.sendEmail(row[RECIPIENT_COL], msgObj.subject, msgObj.text, {

기여자

이 샘플은 에든버러 퓨처 연구소의 학습 설계 및 기술 책임자인 마틴 호크시, 블로거 겸 Google Developer Expert가 만들었습니다.

이 샘플은 Google Developer Expert의 도움을 받아 Google에서 관리합니다.

다음 단계