This is the full source code for the Gmail Twitter Notifier tool that sends out tweets as new messages arrive in your Gmail Inbox. Written in Google Apps Script.
// ====================================
// FOLLOW YOUR GMAIL INBOX ON TWITTER
// ====================================
// Google Docs will tweet as new messages arrive in your Gmail
// See implementation details at http://labnol.org/?p=20990
// Written by Amit Agarwal (@labnol) on 03/12/2012
// Get your own Twitter Keys from dev.twitter.com
var TWITTER_CONSUMER_KEY = "PLEASE_REPLACE_ME";
var TWITTER_CONSUMER_SECRET = "PLEASE_REPLACE_ME_TOO";
// This script watches your Gmail Inbox for all new messages
// but you can specify different Gmail filters. For example:
// in:inbox is:unread has:attachment to:me
var GMAIL_SEARCH_STRING = "in:inbox is:unread";
// This is the main function. Pleas do not modify this code.
function sendTweet() {
var tweet = "";
var threadID = "";
var from = "";
var baseURL = "https://api.twitter.com/1/statuses/update.json?status=";
var url = "";
var status = "";
var oauth = false;
var requestData = {
"method": "POST",
"oAuthServiceName": "twitter",
"oAuthUseToken": "always"
};
var threads = GmailApp.search(GMAIL_SEARCH_STRING, 0, 20);
if(!ScriptProperties.getProperty("lastThreadID"))
ScriptProperties.setProperty("lastThreadID", "0");
for (var i=threads.length-1; i>=0; i--) {
threadID = threads[i].getId();
if (threadID > ScriptProperties.getProperty("lastThreadID")) {
ScriptProperties.setProperty("lastThreadID", threadID);
from = threads[i].getMessages()[0].getFrom();
if(from.indexOf(" <") > 0)
from = from.substring(0, from.indexOf(" <"));
url = " https://mail.google.com/mail/#inbox/" + threadID;
status = from + ": " + threads[i].getFirstMessageSubject();
tweet = baseURL + encodeURIComponent(status.substr(0,110) + url);
// Authorize once per session - @labnol
if (!oauth) {
authTwitter();
oauth = true;
}
var result = UrlFetchApp.fetch(tweet, requestData);
Utilities.sleep(1000);
}
}
}
// The script uses OAuth to connect with your Twitter account
// Thus, you need not share your login credentials with anyone
function authTwitter() {
var oauthConfig = UrlFetchApp.addOAuthService("twitter");
oauthConfig.setAccessTokenUrl("https://api.twitter.com/oauth/access_token");
oauthConfig.setRequestTokenUrl("https://api.twitter.com/oauth/request_token");
oauthConfig.setAuthorizationUrl("https://api.twitter.com/oauth/authorize");
oauthConfig.setConsumerKey(TWITTER_CONSUMER_KEY);
oauthConfig.setConsumerSecret(TWITTER_CONSUMER_SECRET);
}
