GCP/Apps Script

Apps Script로 Sidebar를 이용한 이메일 전송 컴포넌트 개발

whistory 2023. 1. 12. 08:08
반응형

 

정해진 양식으로만 이메일을 보내보는것을 해봤다.

 

 

Apps Script로 Email 보내기 (HTML 양식)

이메일을 보내는 기능을 구현한다. 이메일의 경우는, Google Sheets로 관리되는 거래내역이나 급여내역 등을 다수 전송 할 경우 사용 할 수 있을것이다. 템플릿을 만들고, Google Sheets의 데이터들을

whiseung.tistory.com

 

 

수신자와 내용을 입력해 보낼 수는 없을까?

 

Google Sheets에서 제공하는 sidebar를 이용해 메일을 보내본다.

 

 

일단 상단 메뉴를 만든다.

- Code.gs

// Code.gs

function onOpen() {
  SpreadsheetApp.getUi()
    .createMenu('✉️ email')
    .addItem('📨 email sender', "emailsender")
    .addToUi();
}

 

다음으로 Sidebar를 여는 함수를 만든다.

- Code.gs

// Code.gs

/**
 * Side bar 열기
 */
function openSideBar() {
  var html = HtmlService.createHtmlOutputFromFile("sidebar.html")
                        .setTitle("Send Email");

  SpreadsheetApp.getUi().showSidebar(html);
}

 

다음으로 sidebar 로 사용할 html을 만든다.

 

 

- sidebar.html

// sidebar.html

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <div class="box">
      <p class="title"> To : </p>
      <input type="text" id="reciever" class="text_input" placeholder="수신자" />
    </div>
    <div class="box">
      <p class="title"> CC : </p>
      <input type="text" id="cc" class="text_input" placeholder="참조" />
    </div>
    <div class="box">
      <p class="title"> BCC : </p>
      <input type="text" id="bcc" class="text_input" placeholder="숨은참조" />
    </div>
    <div class="box">
      <p class="title"> Subject : </p>
      <input type="text" id="subject" class="text_input" placeholder="제목 입력" />
    </div>
    <div class="box">
      <p class="title"> Content : </p>
      <textarea id="content" class="text_input textarea" placeholder="내용입력" ></textarea>
    </div>
    <div>
      <input type="checkbox" id="attatch"> 엑셀파일첨부
    </div>
    <div style="margin-top:10px">
      <button id="send">전송</button>
      <button id="send" class="reset">초기화</button>
    </div>
  </body>
</html>

 

 

이제 아까 만든 상단메뉴를 클릭하면, html 파일을 읽어 우측 sidebar가 활성화된다.

 

 

 

다음으로 html 안에서 사용할 함수를 작성한다.

 

 

입력한 값들을 apps script로 전달하는 역할을 한다.

html 파일에서 gs의 함수를 호출 할 때는,

google.script.run.doSomething()

을 이용한다.

 

 

google.script.run 클래스 (클라이언트 측 API)  |  Apps Script  |  Google Developers

이 페이지는 Cloud Translation API를 통해 번역되었습니다. Switch to English 의견 보내기 google.script.run 클래스 (클라이언트 측 API) 컬렉션을 사용해 정리하기 내 환경설정을 기준으로 콘텐츠를 저장하고

developers.google.com

 

 

html 파일에, apps script에서 사용할 함수은 sendEmail() 을 호출하도록 한다.

 

- sidebar.html

// sidebar.html

<script type="text/javascript">
	function sendit() {
		const reciever = document.getElementById('reciever').value;
		const cc = document.getElementById('cc').value;
		const bcc = document.getElementById('bcc').value;
		const subject = document.getElementById('subject').value;
		const content = document.getElementById('content').value;
		const attatch = document.getElementById('attatch').checked;
		
		google.script.run.sendEmail(reciever
		                            , cc
		                            , bcc
		                            , subject
		                            , content
		                            , attatch);
	
	}
</script>

 

- Code.gs

// Code.gs

/**
 * Send Email.
 * 이메일을 이용한 Notify.
 * @param {string} reciever = 받는사람
 * @param {string} cc       = 참조
 * @param {string} bcc      = 숨은참조
 * @param {string} subject  = 제목
 * @param {string} content  = 내용
 */
function sendEmail(reciever, cc, bcc, subject, content, attatch) {
  MailApp.sendEmail({
    htmlBody  : content,
    to        : reciever,
    cc        : cc,
    bcc       : bcc,
    subject   : subject
  });
}

 

 

실행 결과

 

 

 

 

현재 실행되는 Google Sheets이거나, 다른 Google Sheets를 첨부파일로 보내고 싶을 경우도 처리해본다.

- Code.gs

// Code.js

/**
 * Send Email.
 * 이메일을 이용한 Notify.
 * @param {string} reciever = 받는사람
 * @param {string} cc       = 참조
 * @param {string} bcc      = 숨은참조
 * @param {string} subject  = 제목
 * @param {string} content  = 내용
 * @param {string} attatch  = 첨부여부
 */
function sendEmail(reciever, cc, bcc, subject, content, attatch) {
  var result = MailApp.sendEmail({
    htmlBody    : content,
    to          : reciever,
    cc          : cc,
    bcc         : bcc,
    subject     : subject,
    attachments : attatch == true ? createAttatchment() : null
  });
}

/**
 * 첨부파일 만들기
 */
function createAttatchment() {
  const sheet   = SpreadsheetApp.getActive();
  const id      = sheet.getId();
  // 다른 Google Sheets를 보내고 싶을 경우 해당 Google Sheets의 ID를 입력.

  const url     = `https://docs.google.com/feeds/download/spreadsheets/Export?key=${id}&exportFormat=xlsx`;
  const params  = { method:"GET"
                  , muteHttpExceptions:true
                  , headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}
                  };
  const blob    = UrlFetchApp.fetch(url, params).getBlob();
  
  // save to drive
  // DriveApp.createFile(response);

  // return xlxs
  blob.setName(sheet.getName()+".xlsx");
  return blob;
}

 

실행 결과

 

 

 

 

다른 Google Sheets를 첨부파일로 전송하고 싶을경우,

id 만 수기로 입력해주면 된다.

 

//const sheet   = SpreadsheetApp.getActive();
//const id      = sheet.getId();

const id      = "다른 sheet id 입력";

 

 

 

반응형