Skip to content

Instantly share code, notes, and snippets.

@naosim
Created September 15, 2019 21:58
Show Gist options
  • Select an option

  • Save naosim/cb57b0625a940407b120e3a0ad8fdbff to your computer and use it in GitHub Desktop.

Select an option

Save naosim/cb57b0625a940407b120e3a0ad8fdbff to your computer and use it in GitHub Desktop.
gmailを検索する
/**
* メールを検索する
* 注意: 内部でGmailApp.searchを利用しているため、検索結果は多めに取れる。厳密にするには戻り値に対してもう一度フィルターをかける必要がある。
*
* @param {string} searchText
* @param {object} option 省略可
* @return {GmailMessage[]} 日付の昇順でソート済み
*/
function searchMail(searchText, option) {
// optionの初期値セットアップ
if(!option) { option = {} }
if(!option.startThreadIndex) { option.startThreadIndex = 0 }
if(!option.maxThreadCount) { option.maxThreadCount = 200 }
// Gメールから検索
const threads = GmailApp.search(searchText, option.startThreadIndex, option.maxThreadCount);
const messages = GmailApp.getMessagesForThreads(threads);
// スレッドを展開、同一IDの除去
var messageMap = {};
for(var i=0;i<messages.length;i++){
for(var j=0;j<messages[i].length;j++){
messageMap[messages[i][j].getId()] = messages[i][j]
}
}
return Object.keys(messageMap)
.map(function(id) { return messageMap[id] })
.sort(function(a, b) { return a.getDate().getTime() - b.getDate().getTime()})// 昇順
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment