[Google Apps Script] Gmail内に残っている不達メールリストをスプレッドシートに出力する
Gmailから一斉配信してる場合、うまく他システムと連携出来ない場合があったりする。
ので、GASを使ってスプレッドシートに出力したい。
function searchMail() {
const query = '"Delivery Status Notification"'
let offset = 0
const max = 100
const fetchData = (str, pre, suf) => {
const reg = new RegExp(pre + '.*?' + suf, 'g')
if (!str.match(reg)) return ''
return str.match(reg)[0]
.replace(pre, '')
.replace(suf, '')
}
let values = []
while(true) {
let threads = GmailApp.search(query, offset, max)
const messagesForThreads = GmailApp.getMessagesForThreads(threads)
if (threads.length < max) break
for(const messages of messagesForThreads){
const message = messages[0];
const record = [
message.getDate(),
message.getFrom(),
message.getTo(),
message.getSubject(),
fetchData(message.getPlainBody(), 'Final-Recipient: rfc822; ', '\r'), // email
fetchData(message.getPlainBody(), 'Action: ', '\r'), // action
fetchData(message.getPlainBody(), 'Status: ', '\r'), // status
message.getPlainBody().slice(0,600)
]
values.push(record)
}
if(values.length > 0){
SpreadsheetApp.getActiveSheet()
.getRange(offset+2, 1, values.length, values[0].length) // 2,1,1,1 start.
.setValues(values)
values = []
}
offset += max
console.log(offset)
}
}
Gmail.App.search の仕様で一回に500件までしか取得出来ない。ので、検索対象が無くなるまで処理を回し続けてもらう。
上記の場合は、スプレッドシートからスクリプト開いてるパターン。かつ、1行目に
Date | From | To | Subject | Action | Status | Body |
こんな感じのを入れてる。
GmailApp.search のDocumentは下記
https://developers.google.com/apps-script/reference/gmail/gmail-app#searchquery,-start,-max
プランノーツさんの いつも隣にITのお仕事 に記載のあるScriptを参考にさせて頂きました。