LoginSignup
4
3

More than 1 year has passed since last update.

【2023年版】【GAS, LINE Notify, Gmail】gmailの特定のメールをLine通知する方法

Last updated at Posted at 2023-01-29

結論

下記コードをGASに記述するとokです

//LINEにメッセージを送信する
function sendLineMessage(message) {
  // lineのtokenをhogeの代わりに入れる
  const LINE_NOTIFY_TOKEN = "hoge";
  const Authorization = `Bearer ${LINE_NOTIFY_TOKEN}`
  // エンドポイントが変わったら下記変更
  const LINE_ENDPOINT = "https://notify-api.line.me/api/notify"

  const option = {
    "method": "post",
    "headers": {Authorization},
    "payload": {message}
  }
  let response = UrlFetchApp.fetch(LINE_ENDPOINT, option);
}

//メールをチェックし条件に該当するメールをLINEに通知する
function main() {
  let now = new Date();
  let monthStartDate = new Date(now.getFullYear(), now.getMonth(), 1);
  let monthEndDate = new Date(now.getFullYear(), now.getMonth() + 1, -1);
  let firstDay = Utilities.formatDate(monthStartDate, 'Asia/Tokyo', 'yyyy/MM/dd')
  let endDay = Utilities.formatDate(monthEndDate, 'Asia/Tokyo', 'yyyy/MM/dd')

  let query = "is:unread subject:{(検索タイトルA)(検索タイトルB)} after:" + firstDay + "before:" + endDay + "";
  console.log(query)

  //指定した条件でスレッドを検索して取得 
  let myThreads = GmailApp.search(query);
  let threads = GmailApp.getMessagesForThreads(myThreads);
  // threadsは2次元配列
  threads.forEach(messages => {
      // 良くわからないが0番目取得w
      let msg = messages[0]
      // msgはclass
      console.log(msg.getSubject())
      sendLineMessage(msg.getSubject())
      // 既読にする
      // msg.markRead()
    })
  })
}

僕の環境で動いたコード載せときます。
スクリーンショット 2023-01-29 21.11.46.png

lineに通知するためのすること

  1. line notifyでtoken取得
  2. Lineアプリで通知したいline グループに「LINE Notify」を追加
    スクリーンショット 2023-01-29 21.14.04.png
  3. gmailの特定のメールがどの検索でマッチするか探す
  4. gasコーディング

参考にしたサイト

// 参考 コードを参考にしたのはこのひと
https://pg-log.com/gas-gmail-to-line/

// 参考 Gmailの検索条件
https://www-creators.com/archives/5841#:~:text=%E3%81%A6%E3%81%84%E3%81%8D%E3%81%BE%E3%81%97%E3%82%87%E3%81%86%E3%80%82-,%E3%80%8C%E3%81%BE%E3%81%9F%E3%81%AF%20(or)%E3%80%8D%E6%9D%A1%E4%BB%B6%E3%82%92%E6%8C%87%E5%AE%9A%E3%81%97%E3%81%A6%E3%83%A1%E3%83%BC%E3%83%AB,%E3%81%AE%E6%8B%AC%E5%BC%A7%E3%82%92%E4%BD%BF%E3%81%84%E3%81%BE%E3%81%99%E3%80%82

// 参考 Line token取得するところ
https://notify-bot.line.me/ja/

// 参考 GmailApp class参考
https://tonari-it.com/gas-gmail-search-thread/#toc5

注意点など

1. threadsの中身見ないと時間ロスするかも知れない説

main関数の最後付近でthreadsをfor文回してますが、2次元配列になってたり中身が辞書でvalueのところが関数になってる感じなのでlog見ながらが進めた方が良かったです。

2. 迷ったら「var」でok

かっこつけてjavascriptの新しいの使ってます。ですが他の人のコードは「const」や「let」を「var」で記述しています。ほぼ同じ意味ですが、varで問題ないので良くわからない人はvarでokです。

4
3
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
4
3