Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* Observe MailBox
*
* @param {string} condition メール検索条件(require)
* @param {function} onSuccess 条件合致時のコールバック(optional)
* @param {function} onFailure 例外発生時のコールバック(optional)
**/
function observe(condition, onSuccess, onFailure) {
try {
var observer = new GmailObserver(condition),
response = observer.getMails();
return onSuccess ? onSuccess(response) : response;
} catch(ex) {
var response = ex.toString();
return onFailure ? onFailure(response) : response;
}
}
/**
* Constructor GmailObserver
*
* @param {string} condition メール検索条件(require)
**/
function GmailObserver(condition) {
this.condition = condition;
this.setProcessedIds();
}
/**
* Set processed ids
*
**/
GmailObserver.prototype.setProcessedIds = function () {
var ids = PropertiesService.getUserProperties().getProperty(this.condition);
this.processed_ids = ids ? ids.split(',') : [];
}
/**
* Update processed ids
*
**/
GmailObserver.prototype.updateProcessedIds = function () {
PropertiesService.getUserProperties().setProperty(this.condition, this.processed_ids.join(','));
}
/**
* Get mails that match the condition
*
* @return {object} array [GmailMessage, ...]
**/
GmailObserver.prototype.getMails = function () {
var threads = GmailApp.search(this.condition),
result = [];
for(var i in threads) {
var messages = threads[i].getMessages();
for(var j in messages) {
var id = messages[j].getId();
if (this.processed_ids.indexOf(id) == -1) {
result.push(messages[j]);
this.processed_ids.push(id);
}
}
}
this.updateProcessedIds();
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.