Created
April 13, 2013 05:18
-
-
Save mogsdad/5377053 to your computer and use it in GitHub Desktop.
This script was written as the answer to a StackOverflow question about forwarding emails to a rotating list of people. See http://stackoverflow.com/a/15984468/1677912.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Retrieves a given user label by name and forwards unread messages | |
* associated with that that label to a member of the Hunt Group. | |
*/ | |
function huntGroupForward() { | |
// get the label for given name | |
var labelName = "elephant" | |
var label = GmailApp.getUserLabelByName(labelName); | |
if (label == null) throw new Error("No messages for label "+labelName); | |
// get count of all threads in the given label | |
var threadCount = label.getUnreadCount(); | |
if (threadCount == 0) return; // quick exit if nothing to do. | |
var threads = label.getThreads(); | |
var messages = []; | |
for (var i in threads) { | |
if (threads[i].isUnread()) { | |
messages = messages.concat( threads[i].getMessages() ); | |
} | |
} | |
for (var i = 0; i < messages.length; i++) { | |
if (messages[i].isUnread()) { | |
messages[i].forward(nextHuntGroupMember()); | |
messages[i].markRead(); | |
} | |
} | |
}; | |
/* | |
* Global object to store working copy of the Hunt Group | |
*/ | |
var huntGroup = { next : 0, members : [] }; | |
/* | |
* Get the email address of the next Hunt Group Member | |
* to forward a message to. | |
*/ | |
function nextHuntGroupMember() { | |
if (huntGroup.members.length == 0) { | |
// Load members | |
var sheet = SpreadsheetApp.getActiveSheet(); | |
var data = sheet.getDataRange().getValues(); | |
for (var i = 0; i < data.length; i++) { | |
huntGroup.members.push(data[i][0]) | |
} | |
// Make sure we have members | |
if (huntGroup.members.length == 0) { | |
throw new Error("Found no email addresses"); | |
} | |
} | |
// Retrieve next index. Properties are always stored as strings, so | |
// we need to parse the retrieved value to use it as a Number. | |
var next = parseInt(ScriptProperties.getProperty("nextHuntGroupMember")); | |
if (next != null) { | |
huntGroup.next = next; | |
} | |
else { | |
next = 0; | |
} | |
// get next member to be used | |
var nextMember = huntGroup.members[next]; | |
// ... then move on to new next (increment modulo list length) | |
next = ++next % huntGroup.members.length; | |
// store the new next value | |
ScriptProperties.setProperty("nextHuntGroupMember", next); | |
return nextMember; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment