CloudiView

Technology That Matters !

Archive for the tag “source code”

Twitter App for Gmail with Google Apps Script

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);
}

Turn your Twitter into a Gmail Notifier

I am ready to share a little project around Gmail that I have been working on this weekend. The idea is that you can turn your Twitter Timeline into a Gmail Notifier and get notified (via tweets) as soon as new email messages arrive in your mailbox.

And since you can link Twitter to your phone number, you can even get SMS text alerts for new Gmail messages on your mobile phone with the help of Twitter. There’s no programming required and you can be up and running in 5 minutes.

gmail messages in twitter timeline

Connect Gmail and Twitter through Google Docs

Gmail provide an RSS feed of your mailbox but the big problem is that if you have to auto-publish this RSS feed to Twitter, you’ll have to supply your Google account credentials in plain text. That’s not done.

My solution (see source code) uses OAuth with Google Apps Script to link your Gmail and Twitter accounts so you don’t have to share your passwords with anyone.  You have a Google Docs spreadsheet that monitors your Gmail mailbox in the background, say, every 5 minutes. As soon as it finds any new message(s) in your mailbox, it sends out a tweet using your own Twitter app. That’s the overall picture but  here’s how you can implement it:

Step A: Create a new Twitter App for Gmail

  1. Go to twitter.com/signup and create a new Twitter account for your Gmail Inbox – mine is called myGmailInbox.
  2. Confirm your email address, then open the Twitter settings page and check the option “Protect My Tweets” and uncheck the option “Let others find me by my email address.” This is necessary because you don’t want search engines, or any other Twitter user, to see your Gmail tweets even if the tweets will only have the message subject.
  3. Go to dev.twitter.com, sign-in using your new Twitter account and use the following values to create a New Twitter App. [Name=Gmail; Description=Gmail Bot; Website=http://goo.gl/ldAXX; Callback URL=https://spreadsheets.google.com/macros]
  4. Make sure there are no empty spaces in the URL fields else Twitter may give an “Invalid URL format” warning. Accept the terms and conditions, fill in the CAPTCHA and submit the form to create your first Twitter application.
  5. Next go to the Settings Tab of your Twitter Application and change the “Access” mode from “Read only” to “Read and Write” since we want to publish tweets from Google Docs.
  6. Save the Settings, then switch to the tab that says OAuth Tool and make a note of the Consumer Key and the Consumer Secret Key.

Step B: Link Google Docs and Twitter

  1. Go to Google Docs and make a copy of this spreadsheet in your own Docs account.
  2. From Tools –> Script Editor, replace the values of TWITTER_CONSUMER_KEY and TWITTER_CONSUMER_SECRET with their actual values.
  3. Go to Resources –> Current Script’s triggers and create a new Time-driven event for “sendTweet” that triggers every 5 minutes.
  4. Save the trigger and then click Authorize (Grant Access) so that this script can automatically read your Gmail inbox at set intervals to check for new mails.
  5. Go to Run –> SendTweet and it should display another “Authorization Required” message from Twitter. Click Authorize –> Authorize App to allow Google Apps Script publish tweets to your Twitter Gmail account.

Step C: Follow Gmail on Twitter

  1. Log in to your old Twitter account and send a follow request to your new Gmail account on Twitter.
  2. Log in to your new Gmail account and approve the “follow request.”
  3. And we are done. You should now see tweets for new Gmail messages, as they arrive, in your main timeline.

Get SMS Alerts for New Gmail

Should you wish to receive SMS alerts on your mobile phone for new Gmail messages, just open the Twitter profile page of your Gmail bot and turn on Mobile Notifications. This will obviously work only if you have connected (and verified) your mobile phone with your main Twitter account.

One more thing. In the default setup, the Google Script watches your Gmail Inbox for all incoming mails and tweets as soon as it encounters any new messages in the mailbox.

If this results in too many tweets (or SMS text messages), you can specify a different Gmail search filter and thus receive notifications only for messages that you care about. You need to change the value of GMAIL_SEARCH_STRING in line #18.

Post Navigation