35
46

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 5 years have passed since last update.

[Gmail to LINE]GASで新着メールをLINEに転送する

Last updated at Posted at 2019-03-29

#やりたいこと
Gmail → LINE
3月末でIFTTTでGmailがサポート終了となるため、Gmailを転送する機能が使えなくなったので、応急処置として。
調べるとGAS使えばすぐできるみたいなので早速やってみた。

1. GAS(Google App Script)でGmailの新着メールを取得
2. LINEに転送
3. 一定の時間が立つと1~2を繰り返す

#準備

  • LINE NotifyのToken(lineToken)を発行し、コードに貼り付ける。
  • 転送間隔(get_interval)を設定し、GASのトリガーをこれに合わせる

image.png

コード

Gmail_to_LINE.js
var lineToken = "ABC"; //LINE notify token
var get_interval = 30; //〇分前~現在の新着メールを取得 #--トリガーをこれに合わせておく!!


function send_line(Me){
  var payload = {'message' :   Me};
  var options ={
        "method"  : "post",
        "payload" : payload,
        "headers" : {"Authorization" : "Bearer "+ lineToken}  
      };
    UrlFetchApp.fetch("https://notify-api.line.me/api/notify", options);
}


function fetchContactMail() {
  //取得間隔
  var now_time= Math.floor(new Date().getTime() / 1000) ;//現在時刻を変換
  var time_term = now_time - (60 * get_interval); //変換

  //検索条件指定
  var strTerms = '(is:unread after:'+ time_term + ')';
 
  //取得
  var myThreads = GmailApp.search(strTerms);
  var myMsgs = GmailApp.getMessagesForThreads(myThreads);
  var valMsgs = [];
  for(var i = 0; i < myMsgs.length;i++){
    valMsgs[i] = "\n【date】: " + myMsgs[i].slice(-1)[0].getDate() 
                  + "\n【From】: " + myMsgs[i].slice(-1)[0].getFrom()
                  + "\n【Subject】: " + myMsgs[i].slice(-1)[0].getSubject()
                  + "\n【Body】: \n" + myMsgs[i].slice(-1)[0].getPlainBody().slice(0,200); 
  //  myMsgs[i].markRead(); //メッセージを既読にする
  }
    
  return valMsgs;
  
}

function main() {
  new_Me = fetchContactMail()
  if(new_Me.length > 0){
    for(var i = new_Me.length-1; i >= 0; i--){
      send_line(new_Me[i])
    }
  }
}

#参考URL
https://developers.google.com/apps-script/reference/gmail/gmail-app#search(String,Integer,Integer)
https://tonari-it.com/gas-add-contact-mail/
https://qiita.com/3mc/items/39b2c8241c6b52811ad2

35
46
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
35
46

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?