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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//  ====================================
//   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);
}