SYSTEM NOTICE

Auto translation by AI. Be sure, accuracy, nuances and authorial intent may not be fully reflected.
見出し画像

How to receive Gmail notifications on LINE and solutions for when you reach GAS execution limits

Introduction: Setting up Gmail notifications on LINE


I have set up my system to receive notifications from Gmail on LINE as well. The emails I receive include notifications about my children passing through the main gate of their elementary school and notifications regarding their arrival and departure from extracurricular activities. Since I sometimes miss notifications in Gmail, I set it up to send them to LINE so I can be sure to catch them.
When I shared the setup method in the following note, many people read it, and I received very happy comments and DMs saying things like, "This is so convenient!" Thank you very much!

I was very surprised to receive a notification from note saying it was "one of the most read articles last week."



The Problem: Reaching the Google Apps Script execution limit


I am writing a program for this process in Google Apps Script, but I was confused when I started getting an error message that means I reached the daily usage limit:"Exception: Service invoked too many times for one day: gmail.".

In this article, I would like to share the cause of this error message and how to solve it.

Considering Solutions: Optimizing script execution time


Google Apps Script has a daily execution time limit of 5400 seconds (90 minutes) for free accounts. Therefore, if you want to set a trigger every minute for 24 hours (1440 executions per day) with a free account, you need to keep each script execution time within 3.75 seconds.

The script I had written previously took about 4 to 7 seconds per execution, so the total daily execution time far exceeded 5400 seconds, causing me to hit the limit.

It was taking about 4 to 7 seconds per execution.

You can check how to see the processing time from the "Executions" section on the left.


Practical Approach: Efficiently retrieving unread messages

To solve this problem, I need to increase the execution efficiency of the script. Specifically, I aimed to reduce processing time with the following approach.

  • Retrieve only unread messages: Initially, I was retrieving all threads with a specified label, but this was a waste of time because it processed many unnecessary messages. So, I changed it to retrieve only unread messages with the specified label. As a result, I was able to significantly reduce processing time and keep it under 1 second per execution.

I was able to keep it under 1 second per execution!

Improved Script: Efficient notification system

To efficiently retrieve only unread messages in Google Apps Script, use the GmailApp search method to execute a specific query. This method uses the Gmail search operator "is:unread" to filter unread messages. As shown below, you can retrieve only unread messages belonging to a specific label.

// 「my_label」ラベルの未読メッセージを取得
var threads = GmailApp.search('label:my_label is:unread');

By specifying a query with search in this way, you can exclude unnecessary messages in advance and improve processing efficiency.


Here is the complete improved script.


function sendNotificationForUnreadMessages() {
  var accessToken = '****************; // LINE Notifyのアクセストークンをここに置き換える
  var labelName = 'ラベル名'; // 通知を受けたいGmailのラベル名
  var searchQuery = 'label:' + labelName + ' is:unread'; // ラベルと未読の条件を指定
  var threads = GmailApp.search(searchQuery); // 検索クエリに基づいてスレッドを取得
  var messages = GmailApp.getMessagesForThreads(threads); // スレッド内のメッセージを取得

  for (var i = 0; i < messages.length; i++) {
    for (var j = 0; j < messages[i].length; j++) {
      var message = messages[i][j];
      if (!message.isUnread()) continue; // 念のため未読のメッセージのみを確認(この行は基本的に不要)

      var subject = message.getSubject();
      var bodyText = message.getPlainBody();
      var snippet = bodyText.substring(0, 70); // 本文の最初の70文字を取得

      // LINE Notifyに送信するメッセージを準備
      var payload = {
        'message': '新しいメール: ' + subject + '\n' + snippet
      };

      // LINE Notifyにメッセージを送信するためのオプションを設定
      var options = {
        'method': 'post',
        'payload': payload,
        'headers': {'Authorization': 'Bearer ' + accessToken}
      };

      // LINE Notify APIを呼び出して通知を送信
      UrlFetchApp.fetch('https://notify-api.line.me/api/notify', options);

      // 処理したメッセージを既読にする
      message.markRead();
    }
  }
}

Comparison with the original script

While the original script retrieved all threads associated with the specified label, the improved script reduces execution time by narrowing the scope to only unread messages.

function sendNotification() {
  var accessToken = '***************; // LINE Notifyのアクセストークン
  var label = GmailApp.getUserLabelByName('ラベル名'); // 通知を受けたいGmailのラベル名
  var threads = label.getThreads();

  // メッセージをスレッドごとに一括取得
  var messages = GmailApp.getMessagesForThreads(threads);

  for (var i = 0; i < messages.length; i++) {
    for (var j = 0; j < messages[i].length; j++) {
      var message = messages[i][j];
      if (!message.isUnread()) continue; // 未読のメッセージのみ処理
      var subject = message.getSubject();
      var bodyText = message.getPlainBody(); // メールのプレーンテキスト本文
      var snippet = bodyText.substring(0, 70); // 本文の最初の70文字を取得
      var payload = {
        'message': '新しいメール: ' + subject + '\n' + snippet
      };
      var options = {
        'method' : 'post',
        'payload' : payload,
        'headers' : {'Authorization': 'Bearer ' + accessToken}
      };
      
      UrlFetchApp.fetch('https://notify-api.line.me/api/notify', options);
      message.markRead(); // 処理したメッセージを既読にする
    }
  }
}

----------
The book I wrote has been published!
\Born from Twitter/
A book about slightly scientific home play

Amazon Best Sellers Rank
Early Childhood Education Category Paid Top 100
It reached #1 Bestseller!✨
Thank you!

Available on Kindle Unlimited and in paperback!




いいなと思ったら応援しよう!

宮崎真理|『AI×家事』著者 ❤️応援ありがとうございます。いただいたご支援は「めんどくさい」を解決する新しいテクノロジーの検証費や、3兄弟との楽しい実験材料費に大切に使わせていただきます。皆さまの応援が力になります!

この記事が参加している募集