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

코딩 수준: 초급
시간: 10분
프로젝트 유형: 커스텀 메뉴가 있는 자동화

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

목표

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

이 솔루션 정보

Google Sheets의 데이터로 이메일 템플릿을 자동으로 채웁니다. 이 이메일은 Gmail 계정에서 전송되므로 답장합니다.

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

메일 병합 예

작동 방식

Gmail 임시 템플릿을 만들 때 Sheets 스프레드시트의 데이터에 해당합니다. 각 열 헤더 자리표시자 태그를 나타냅니다. 스크립트는 각 자리표시자를 스프레드시트의 해당 위치로 자리표시자 태그를 사용하세요.

Apps Script 서비스

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

기본 요건

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

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

스크립트 설정

Apps Script 프로젝트 만들기

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

수신자 또는 이메일의 이름을 변경하는 경우 전송 열에서 해당 코드를 업데이트해야 합니다. 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)

위 샘플에서 noReply 매개변수는 여전히 주석 처리됩니다. 이는 replyTo 매개변수가 설정되어 있기 때문입니다.

이메일에 유니코드 문자 포함

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

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

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

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

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

참여자

이 샘플은 마틴 호크시(Marin Hawksey)의 학습 설계 및 기술 책임자인 에든버러 미래 연구소, 블로거, Google Developer Expert

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

다음 단계