2
3

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のメールをSlackに転送する

Posted at

GoogleAppsScriptでGmailのの内容をSlackに転送するシステムを作りました。

Gmailのメールを取得する

Gmailの受信リストを取得するのにGmailAppを使います。

Gmailのフィルタで取得するメールを絞る

特定の条件のメールを探すのに、search()メソッドを使います。条件フィルタは、専用の演算子を使って作ります。
例えば、以下のときは未読になっているメールに絞ります。

GmailApp.search("is:unread")

フィルタのための演算子は、演算子を使ったフィルタ条件の記述方法を参照してください。

その他メソッド

GmailAppの各メソッドを使って取得できる項目は以下の通りです。

  • getDate():受信日
  • getFrom():送信者
  • getSubject():件名
  • getPlainBody():本文

転送するメールを選別する

TwitterやGoogleなどのログイン通知、広告など、Slackに送信する必要のないメールを選別する関数を作成します。
まず、Slackに送信しないメールアドレス (@より後ろ) をまとめた配列を用意します。

var ls = ["accounts.google.com", "twitter.com", "google.com", "github.com", "youtube.com", "docs.google.com"];

任意のアドレスと配列内のアドレスがmatchというメソッドで一致したときTrueを返します。
つまり、メインの関数ではこの関数を呼び出し、FalseになったメールをSlackに転送すれば良いのです。

matchメソッドは文字列ではなく、正規表現フォーマットにする必要があります。
正規表現にフォーマットする際は、RegExpを使います。
参考:Google Apps Scriptで正規表現を使って必要な情報を抽出する最も簡単なスクリプト

function isBotAddress(mail) {
  var ls = ["accounts.google.com", "twitter.com", "google.com", "github.com", "youtube.com", "docs.google.com"];
  for (var i=0; i < ls.length; i++) {
    // 正規表現のフォーマット化
    var botAddress = new RegExp(".*@"+ls[i]);
    // 一致したときTrueを返す
    if(mail.match(botAddress)) {
      return true
    } else {
      continue
    }
  }
}

Slackに転送しないメールが増えたときはは、そのアドレスを配列に足すだけで解決します。

全体

getFrom()は、送信者のメールアドレス以外のものも含まれているので、事前にメールアドレスを抽出します。
参考:Google App Script(GAS)でメールを抽出してSpreadSheetに書き出す

var fromAddress = msg.getFrom().replace(/^.*<(.*?)>.*$/, "$1");

スクリプトを紹介すると、

  • 返信がスレッドとして繋がっているので2次元配列になっているのでFor文を2回使っています。
  • markRead()でSkackに送信したメールを既読にします。
  • Webhookを使ってSlackに転送する関数は、Googleformからのslack通知設定方法を参考に作成しています。
  • 本文部分を```で括ると、Slackではコードブロックで表示されます。(表示画面参照)
function tenso(){
  var threads = GmailApp.search("is:unread");
  var msgs = GmailApp.getMessagesForThreads(threads);
  for(var i = 0; i < msgs.length; i++) {
    var msgsInthread = msgs[i];
    for (var j=0; j < msgsInthread.length; j++) {
      var msg = msgsInthread[j];
      // アドレス部分を取り出す
      var fromAddress = msg.getFrom().replace(/^.*<(.*?)>.*$/, "$1");
      Logger.log(fromAddress);
      if (isBotAddress(fromAddress)) {
        Logger.log("This is mail from BotAddress.");
      } else {
        var date = msg.getDate();
        var from = msg.getFrom();
        var subject = msg.getSubject();
        var body = msg.getPlainBody();
        var mailBody = "メールを転送します。\n"+ from +"さん\n日付:"+ date + "\n*件名:"+ subject + "*\n\n```"+ body+"```";

        // Go To Slack        
        sendToSlack(mailBody, "チャンネル名");
      }
      // 既読にする
      msg.markRead();
    }
  }
}

以下のようにSlackに表示されます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?