Wednesday, March 19, 2008

Automated (Hacking out) subscription to Google Alerts

Recently I have been trying to write a "automated email notification" software program to subscribe to email notifications from Google Alerts. A quick look at the news groups for Google API show up that there is not API to do a subscription programatically .... time to get the hand dirty digging through the web interface :)


A quick look at the source yields the following information

  • action="/alerts/create?hl=en&gl=" method="POST"
This means url encoding will not work and that we will need to do a http post instead. Fortunately this is quite easy to do in C#. The next step is to figure out the parameters being passed.

Search terms name="q"
size="20" maxlength="256"

Type name="t"
value="1" News
value="4" Blogs
value="2" Web
value="7" Comprehensive
value="9" Video
value="8" Groups

Frequency name="f"
value="1" once a day
value="0" as-it-happens
value="6" once a week

Email name="e"
size="20" maxlength="256"

As such, an example of the parameters for the Search term "Google" in News as-it-happens being emailed to myemail@email.com will be as follows after URL encoding:
  • q=help&t=1&f=0&e=myemail%40email.com
Hard coding this will yield the following code:

public string TestGoogleAlertSubscription()
{
System.Net.WebRequest req = System.Net.WebRequest.Create(@"http://www.google.com/alerts/create");
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";

byte[] bytes = System.Text.Encoding.ASCII.GetBytes("q=help&t=1&f=0&e=myemail%40email.com");
req.ContentLength = bytes.Length;

System.IO.Stream os = req.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
os.Close();

System.Net.WebResponse resp = req.GetResponse();
if (resp == null) return null;

System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream());
return sr.ReadToEnd().Trim();
}
Running this VS2005 using debug mode yields the following response showing a successful subscription.

Checking the inbox will show the verification email.

No comments: