LoginSignup
1
0

More than 1 year has passed since last update.

GASでGmailをLINEに自動転送する

Posted at

直近1時間に受信したGmailをLINEに自動転送するスクリプト(GAS)

関数mainを1時間おきのトリガーで設定すればok :ok_hand:

const LINEToken = "xxxxxxxx"; //LINE notify token

function main() {
  try {
    const messageList = getMessageListLastOneHour();
    for(let i = 0; i < messageList.length; i++) {
      sendToLINE(messageList[i]);
    }
  } catch(error) {
    Logger.log(error);
  } 
}


//検索対象にしたい送信元メールアドレスリスト(任意)
function getTargetFromEmailList() {
  return [
    'xxx@xxx',
  ];
}  

//直近1時間に受信したメールを検索して取得する
function getMessageListLastOneHour() {
  //検索条件
  let searchString = '(newer_than:1h';
  const fromEmailList = getTargetFromEmailList();
  if (fromEmailList.length > 0) {
    searchString += 'from:' + fromEmailList.join(' OR from:');
  }
  searchString += ')';
 
  //取得
  const myThreads = GmailApp.search(searchString);
  const myMsgs = GmailApp.getMessagesForThreads(myThreads);
  let targetMsgs = [];
  for(let i = 0; i < myMsgs.length;i++){
    const message = myMsgs[i].slice(-1)[0];
    targetMsgs[i] = " " + (message.getDate().getMonth()+1) + "/"+ message.getDate().getDate()
    + " " + message.getDate().getHours() + ":" + message.getDate().getMinutes()
    + "\n[from]" + message.getFrom()
    + "\n\n[subject]" + message.getSubject()
    + "\n\n[body]" + message.getBody(); 
  }

  return targetMsgs;
}

// LINEに転送する
function sendToLINE(message) {
  const payload = {'message' : message};
  const options ={
    "method"  : "post",
    "payload" : payload,
    "headers" : {"Authorization" : "Bearer "+ LINEToken}  
  };
  UrlFetchApp.fetch("https://notify-api.line.me/api/notify", options);
}

こんな感じ

IMG_6F68821DC7D9-1.jpeg

参考

メールをラインに転送する方法! iPhone/AndroidのGmailを自動でLINEに通知しよう

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0