GCP/Apps Script

Apps Script로 URL호출을 통한 이메일 보내기 (API처럼 사용하기)

whistory 2023. 3. 17. 10:41
반응형

 

💡 App Script로 생성한 웹 앱의 URL을 호출하여
      호출 시 전달 받은 파라미터를 이메일 컨텐츠로 전송해보겠다.

 

아래 두가지를 응용하여 API처럼 URL 호출만으로 이메일을 전송해보려고 한다.

 

 

Apps Script로 간단한 웹페이지 생성하기

Apps Script로 간단한 웹페이지를 생성 할 수 있다. 이 웹페이지에서 Bigquery, Database, Google sheets로 데이터를 입력(입력)할 수 있다. Simple Trigger인 doGet()를 이용한다. function doGet(e) { return HtmlService.createT

whiseung.tistory.com

 

 

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

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

whiseung.tistory.com

대략적은 프로세스는 아래와 같다.

  1. doGet() 함수를 이용해, name과 message라는 파라미터를 받는다.
  2. 이메일 전송 함수를 호출한다.
  3. 이메일 전송 함수에서 결과값을 반환한다.
  4. 결과값을 JSON 형태로 반환한다.

 

 

Code.gs

function doGet(e) {
  Logger.log(JSON.stringify(e));
  const name = e.parameter['name'];
  const message = e.parameter['message'];

  Logger.log(e.parameter['name']);
  Logger.log(e.parameter['message']);

  if ( name != null && message != null ) {
    const sendResult = sendEmail(name, message);
    const result = ContentService.createTextOutput(JSON.stringify(sendResult))
    				  .setMimeType(ContentService.MimeType.JSON);
    return result;
  }
}

/**
 * Send Email.
 * 이메일을 이용한 Notify.
 * @param {string} name     = 받는사람
 * @param {string} message  = 제목
 */
function sendEmail(name, message) {
  try {
    const recipient = "whiseung@naver.com";
    const subject   = "Apps Script Email Test";

    const htmlTemplate = HtmlService.createTemplateFromFile("mail1.html");
    
    htmlTemplate.name = name;
    htmlTemplate.message = message;
    const htmlBody = htmlTemplate.evaluate().getContent();
    
    MailApp.sendEmail({
      to: recipient,
      subject: subject,
      htmlBody: htmlBody
    });

    return {"result": "200", "message" : "Success!"};

   } catch (error) {
      Logger.log(error.message);
      return {"result": "999", "message" : error.message};
  }
}

mail1.html

<!DOCTYPE html>
<html>
    <head>
    	<base target="_top">
    </head>
    <body>
        <p>Hello <?= name ?></p>
        <p><strong><?= message ?>.</strong></p>
        <p>Thanks.</p>
    </body>
</html>

 

 

 

get 방식으로 파라미터 전달

https://script.google.com/macros/s/deploy_id/dev?name=Tom&message=GoodLuck!

파라미터가 없으면 위와같은 화면이 뜰것이다.

 

 

 

전송결과를 json 으로 reutrn

 

URL 호출을 통해 전송 받은 email

 

 

이와 같은 기능을 통해,

매일 돌아가는 배치 프로세스나 주기적인 notify가 필요한 경우에

URL호출을 통해 알림을 제공 할 수 있을 것이다.

 

mail 알림 뿐만 아니라 Telegram bot 으로도 가능할 것이다.

 

 

Apps Script로 공공데이터 포털 openAPI 데이터를 매일 Telegram으로 받기

매일 주택청약 확인을 위해 홈페이지를 들어갔다. https://www.applyhome.co.kr/ai/aib/selectSubscrptCalenderView.do#a 매일 홈페이지를 들어가지 않고, 공공데이터 포털에서 제공하는 데이터를 Telegram 메세지로

whiseung.tistory.com

 

반응형