30
38

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

GoogleAppsScriptでgmailをLINEに転送

Last updated at Posted at 2021-02-17

こちらの記事のスクリプトを改造しました。

こんなサービスもあるみたいなので、自分でやる必要もないのですが、ちょっと凝った応用をしたかったり、あまりよく知らない企業のサービスにメールを転送するのが嫌な場合もありますよね。

変更点

  • 前回実行時に処理したメールの message ID を覚えておき、同じメールを二度転送しない
  • スレッドの最後のメールだけでなく、全てのメールを転送

コード

const lineToken = "自分で取得したトークンに置き換えてね"; // LINE Personal Token
const query = "label:転送したいメールのラベル" // gmailの検索クエリ
const thresholdInMinutes = 60; // 何分前のメールまでチェックするか(同じメールは二度転送しないので、スクリプトの実行間隔より長くて良い)

const scriptProps = PropertiesService.getScriptProperties();

function sendToLine(message){
  const payload = { message };
  const options = {
   method: "post",
   payload: payload,
   headers: { Authorization: `Bearer ${lineToken}` },
  };
  UrlFetchApp.fetch("https://notify-api.line.me/api/notify", options);
}

function getPrevMessgeIds() {
  try {
    return JSON.parse(scriptProps.getProperty("messageIds") || "[]");
  } catch (error) {
    console.log("getPrevMessageId: error:", error);
    return [];
  }
}

function fetchMails() {
  const now = new Date().getTime();
  const threshold = now - (60 * 1000 * thresholdInMinutes);

  const threads = GmailApp.search(`(${query}) after:${Math.floor(threshold / 1000)}`);
  const threadMessages = GmailApp.getMessagesForThreads(threads);
  const prevMessageIds = getPrevMessgeIds();
  console.log("prev message ids", prevMessageIds);
  const lineMessages = threadMessages.flatMap((messages) =>  {
    return messages.filter((message) => {
      return threshold <= message.getDate().getTime() && prevMessageIds.indexOf(message.getId()) < 0;
    }).map((message) => {
      return `\n[from] ${message.getFrom()}\n[subject] ${message.getSubject()}\n\n${message.getPlainBody()}`;
    });
  });
  const messageIds = threadMessages.flatMap((messages) => {
    return messages.map((message) => message.getId());
  });
  console.log("current message ids", messageIds);
  scriptProps.setProperty("messageIds", JSON.stringify(messageIds));
  return lineMessages;
}

function main() {
  const messages = fetchMails();
  console.log(`${messages.length} message(s) found`);
  messages.forEach(sendToLine);
}
30
38
1

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
30
38

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?