1
2

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に届くAWSの請求書を毎月自動でGoogleドライブに保存する

1
Last updated at Posted at 2021-06-14

はじめに

こんにちは。最近実家の畑に知らない人が勝手に耕したりしているそうで、母親がばちぼこぷんぷんまるで、警察のお世話になりそうです、筆者です :angry:

さて、今回はみんな大好きAWSから、毎月メールで届く請求書をGoogleドライブに保存しようと思います!

前提

  1. 毎月4日に届いている(気がする).
  2. 送信元メールアドレスは aws-receivables-support@email.amazon.com.
  3. メールの件名は Amazon Web Services Invoice Available [Account: 123456789012] [Invoice ID: 123456789] な感じ.`

手順

  1. 当月既に処理済みの場合は正常終了.
  2. 当月届いた当該メールを検索.
  3. 2のメールからPDFファイルを取得.
  4. 3のPDFファイルを指定のGoogleドライブアップロードする.
  5. 4のPDFファイル名をYYYYMMに変更.
  6. 2のメールをゴミ箱に移動.
  7. もし2でメールが存在しなかった場合は翌日の同時刻に再実行トリガーをセットして正常終了.
  8. 1-7を毎月5日に定時実行する.

実スクリプト

手順8のトリガーは別途設定して下さい!:bow:

const main = () => {
  const now = new Date()
  const ymd = Utilities.formatDate(new Date(now.getFullYear(), now.getMonth(), 1), 'Asia/Tokyo', 'yyyy/MM/dd')
  const folder_id = 'xxxx'
  const file_name = Utilities.formatDate(new Date(now.getFullYear(), now.getMonth(), 1), 'Asia/Tokyo', 'yyyyMM')
  const mail_from = 'aws-receivables-support@email.amazon.com'
  const subject = 'Amazon Web Services Invoice Available'

  // 手順1
  if (0 < DriveApp.getFolderById(folder_id).getFilesByName(file_name).hasNext()) {
    return
  }

  // 手順2
  const threads = GmailApp.search(`from:("${mail_from}") subject:("${subject}") has:attachment after:${ymd}`, 0, 1)
  let messages, message, attachment, uploaded = false
  for (i in threads) {
    if (uploaded) {
      break
    }

    messages = threads[i].getMessages()
    if (messages.length < 1) {
      break
    }

    message = messages[0]
    if (message.isInTrash()) {
      // ゴミ箱にあるメールはスルー.
      break
    }

    // 手順3
    attachment = message.getAttachments()[0]

    // 手順4
    const file_id = DriveApp.getFolderById(folder_id).createFile(attachment).getId()

    // 手順5
    DriveApp.getFileById(file_id).setName(file_name)
    uploaded = true

    // 手順6
    message.moveToTrash()
  }

  if (! uploaded) {
    // 手順7
    ScriptApp
      .newTrigger('main')
      .timeBased()
      .atDate(now.getFullYear(), now.getMonth() + 1, now.getDate() + 1)
      .create()
  }
}

スクリプト実行

初回実行時に、権限を要求されるので許可してください:pray:

a.png

実行するとドライブにAWSの請求書が追加されました!
a.png

Gmailも確認すると当該メールがゴミ箱に移動しています:ok_hand:

おわりに

これでいらないメールが消えて、必要なファイルだけちゃんとドライブにアップロードされるようになりました:v:

皆さんもぜひ!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?