Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
41
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

posted at

updated at

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

やりたいこと

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
41
Help us understand the problem. What are the problem?