LoginSignup
4
4

More than 3 years have passed since last update.

【GAS】Gmailで自由に転送する

Last updated at Posted at 2019-05-07

動機

Gmailでは特定のメールを転送することは出来る。しかし相手側に許可を求めるメールが送信され手続きが必要であり非常に面倒。それでいて細やかな変更はできない。そこでGASの力で自由に転送する。

GAS

function transferEmail() {
  transferEmailBySearch('fuga@example.com', 'from:(hoge@example.com)', 'hogeについての転送')

  function transferEmailBySearch(address, searchWord, subject) {
    const now = Math.floor(new Date().getTime()/1000); 
    const intervalTime = 8 //8時間毎に実行されるように設定してください
    const term = now - 3600 * intervalTime; 

    const str = searchWord + ' ' + 'after:' + term;

    const myThreads = GmailApp.search(str, 0, 30);
    const myMsgs = GmailApp.getMessagesForThreads(myThreads);

    if(myMsgs.length == 0)
      return null;

    myMsgs.map(function(msgs) {
      const msg = msgs[0];   
      MailApp.sendEmail({
        to: address,
        subject: subject,
        body: 'お世話になっております。\n\n以下転送内容です。よろしくお願いいたします。\n\n' +
              '日時:'+ msg.getDate() + 
              '\n送信元:' + msg.getFrom() + 
              '\n件名:'+ msg.getSubject() + 
              '\n\n' + msg.getPlainBody(),
        attachments: msg.getAttachments()
      });
    });
  }
}

コメント

処理はGmailで8時間毎に検索をかけてスレッド取得→指定したアドレスに転送だけです。
本当はmyMsgsのスレッドすべてのメールに対して受信時刻を確認しなければ転送漏れが出るかもしれない。

参考文献

Gmail Apps Script - Gmail Service | Apps Script | Google Developers
https://developers.google.com/apps-script/reference/gmail/
公式のリファレンス。必読。

4
4
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
4
4