Click here to Skip to main content
Click here to Skip to main content

Gmail Agent API v0.5 / Mail Notifier & Address Importer

By , 6 Jul 2004
 
Prize winner in Competition "C# Jun 2004"

What is it?

There are two distinct components here: an open source Gmail API written for the .NET framework, and a proof of concept Windows application built on top of that API that provides basic remote Gmail functions.

I developed these tools in the hopes of encouraging others to create interesting Gmail services. Admittedly, this project may not have a very long shelf life, as Sergey has intimated possible mail forwarding and RSS support, not to mention Gmail's recent listing of upcoming features (Gmail login required) that estimates a slew of features that are listed as “working on it” or “we'll try”. The address book import is currently listed as “sometime soon” but it's actually available now in the Contacts window. As Sergey mentioned, an enterprise version of Gmail would be well received, and I have no doubt that there would an API to go along with that (I recently integrated a Google Search Appliance, and can attest to its extensibility). Whether or not Google is interested in pursuing such features for the public side remains to be seen. Nonetheless, I hope to keep this project going, and wouldn't mind joining the Gmail team — there are lots of features I'd like to see implemented in Gmail.

About the Gmail Agent Applet

I'm sure most of you are more interested in the applet, so here are the features:

  • Multiple account support
  • Balloon notification of new messages with message preview
  • Address book view and import (from tab-delimited text files)

The system requirements are:

  • Windows 2000, or higher
  • Microsoft .NET Framework v1.1

I haven't tried this with Mono — I doubt it works, but if it does, please let me know. If you are interested in POP access to Gmail, check out Pop Goes the Gmail (also a .NET project).

This is a proof of concept application, and there are plenty of idiosyncrasies. It works great for me, but your results may vary. I welcome anyone who wants to contribute to polishing this app.

About the Gmail Agent API

The goal of the API is to provide an extensible foundation for interfacing with Gmail. The objects in this namespace should be abstracted enough to be able to be adapted to any future changes Gmail makes.

Read the documentation for Gmail Agent API 0.5 to see what's available.

The main workhorse of this class is GmailAdapter. It is responsible for communicating with Gmail and maintaining the login and session information through the duration of the application. The GmailSession object holds all the state information for a single Gmail account, including a GmailThreadCollection of GmailThread objects. The GmailContact object represents a single Gmail address book entry. Again, GmailAdapter provides the methods to fill a GmailContact with information from Gmail.

Connection Overview



One oddity with the API is that it uses TLS instead of SSL for the encryption layer. For reasons unknown, the SSL provider was extremely intermittent and often failed to establish a secure link so I manually set the ServicePointManager to use TLS 1.0. This seems to be a common problem among .NET developers, and if anyone has a stable solution, I'd love to hear about it.

Here is a bare-bones example of how to establish a connection with Gmail using the API:

// init new adapter
GmailAdapter gmail = new GmailAdapter();

// create new session and assign username and password
GmailSession myAccount = new GmailSession();
myAccount.Username = "googler";
myAccount.Password = "showmethemoney";

// login and retrieve mailbox info
GmailAdapter.RequestResponseType loginResult = gmail.Refresh(myAccount);

// display mailbox info
if(loginResult == GmailAdapter.RequestResponseType.Success) {

    // show new inbox count
    Console.WriteLine("New Threads: " + myAccount.DefaultSearchCounts["Inbox"]);

    // if new threads exist, show the subject of the first one
    if(myAccount.UnreadThreads.Count > 0) {
        GmailThread newThread = (GmailThread)myAccount.UnreadThreads[0];
        Console.WriteLine("Latest thread subject: " + newThread.SubjectHtml);
    }
}

About the Gmail engine and protocol

You've probably noticed that Gmail's interface is extremely fast when compared to other web-based email systems like Yahoo! Mail and Hotmail. This is a result of Gmail's placement of the UI engine on the client-side as a JavaScript module. Whenever you log in to Gmail, a copy of the UI engine is loaded into one of the HTML page frames and remains there for the duration of your session (credit has to be given to Oddpost for being the first ones who perfected this idea). Subsequent actions from the Gmail interface are then routed through the Gmail UI engine in your browser, which in turn makes HTTP requests (via the XmlHttpRequest object) to the Gmail server, interprets the DataPack (more on this later), and updates the UI dynamically. In contrast, Hotmail and Yahoo! Mail follow traditional web application models and reload the entire UI after almost every action.

The item most relevant to this project is what I refer to as the “DataPack”, a base HTML file that contains only JavaScript array declarations that the UI engine parses and then uses to determine what to update. The advantages of this should be immediately obvious: reduced traffic load, and increased functionality — especially for developers who no longer have to resort to crude “screen scraping” techniques to interface with web applications. Although the ideal situation for external developers would be an XML-based DataPack, the JavaScript version is sufficient (and I suspect it was chosen for performance reasons as well).

The DataPack format consists of individual “DataItems”, or JavaScript arrays wrapped in a envelope function. An example:

D(["ts",0,50,106,0,"Inbox","fd36721220",154]);

The function D() references a runtime evaluator within the Gmail engine, which then interprets the attached array parameters. The "ts" element indicates that this is a threadlist summary item, and the subsequent elements denote start index, threads per page, estimated total, threadlist title, threadlist timestamp, and total threads. This is the same format that is applied to all array parameters sent through the DataPack:

[<DataItem_name>(,<custom_attribute>)]

The mappings to all the DataItems can be found in the engine code source (/gmail?view=page&name=js). For instance, qu contains quota information, while ct contains category (a.k.a. labels) definitions. Read through that file if you really want to get everything you can out of Gmail.

Determining the right URL to retrieve the DataPack is pretty straightforward, as most requests will return the same basic information, such as quota, category count, and inbox count. The main thing that changes is the threadlist summary, which depends on what page you're looking at. All the main folders — inbox, starred, trash, spam, etc. — are all really just pre-defined searches within Gmail. For example, the inbox DataPack URL is:

/gmail?search=inbox&view=tl&start=0&init=1&zx=

The search query for all unread threads is:

/gmail?search=query&q=is%3Aunread&view=tl&start=0&init=1&zx=

The main parameters are search= and q=, which define what set of threads the user is requesting. The zx= parameter is a proxy cache defeater, and I've omitted it here for brevity. See GmailAdapter.MakeUniqueUrl() for more information.

Gmail exploits another advantage of the DataPack model to increase efficiency by allowing for an empty document. This is employed by the 2-minute auto-refresh request. The inbox URL adds a few more parameters:

/gmail?view=tl&search=inbox&start=0&tlt=fd8dfa2e31&fp=c155594240dcc7cb&auto=1&zx=

The tlt= parameter is the thread list timestamp, which is treated like a checksum in determining the state of the client versus the mailbox state on the server. If the client timestamp is older than the one on the server, then a full DataPack is sent. Otherwise, Gmail sends an essentially empty DataPack.

Feedback

Feel free to contact me with any questions. Or, you can just leave a comment over here.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Johnvey Hwang
Web Developer
United States United States
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionException in GMailAdaptermemberMember 834084928 Oct '11 - 23:35 
Hey guys   I want to use the gmail API J. Hwang introduced. But the gmailadapter throws an exception if using rawResponse = MakeWebRequest(location, "GET", GOOGLE_LOGIN_URL, null, false); In MakeWebRequest the exception comes from the cookieContainer in...
GeneralCross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on.membervarbace27 Apr '11 - 0:37 
Change the Update function to use the Delegate.   // update an existing icon delegate void UpdateDelegate(); private void Update() { if ( !m_messageSink.InvokeRequired ) { NotifyIconData data = new NotifyIconData(); ...
Generalsame here...not getting access to accountmembersawantprashant6 Jul '10 - 20:20 
:(
GeneralLogin Failed Even after giving the valid credentials.memberMadhukar Mudunuru11 Sep '07 - 3:40 
I used the Gmail Agent Dll and tried.   I created a Session and posted   Even after giving the valid login credentials i am getting the result as failed.   the following is the code which i used. I am getting the lr as loginfailed.   GmailAPI.GmailSession myacc =...
GeneralCode is not workingmemberkulvinder_200026 Jul '07 - 1:49 
Dear Author,   Kindly fix the bugs so that we can use the code properly.   I just hit Contacts and it gave me an error at :   int addressBlockEnd = this._rawDataPackResponse.IndexOf("]];", addressBlockStart) + 2;   Kulvinder Singh
Generalimport contacts from any mailmemberneerubee11 Jul '07 - 0:11 
i tried u r code.but it's not working.actually for any mail like gmail,yahoo,hotmail how can we retrieve the contacts just by giving user name and password from asp.net.   i saw php scripts but i am not getting same thing for asp.net.   if any body knows please post here.
GeneralRe: import contacts from any mailmemberRahana A27 Jul '09 - 0:14 
hi   did u got any reply from anyone?
GeneralSample for gmail contactmemberwailoon.ho30 May '07 - 19:16 
Hi there, i hope to retrieve contacts from gmail. i have tried to use the GmailContactCollection, but i hit an error which is "index out of range" at GmailAdapter.cs, GetContacts() function, "int addressBlockEnd = this._rawDataPackResponse.IndexOf("]];", addressBlockStart) + 2;" code.  ...
GeneralRe: Sample for gmail contactmemberJohnvey Hwang30 May '07 - 20:18 
Unforunately, this project is no longer being maintained and does not function properly. I would highly suggest just using the export feature within Gmail itself to obtain all of your contacts.   - J
GeneralRe: Sample for gmail contactmemberwailoon.ho30 May '07 - 20:39 
do you mind tell me where can i get the information of that feature??
QuestionIt's not workingmemberH. S. Masud22 May '06 - 1:32 
Hi, I tried to use it. I setup my account. But I'm getting an exception while I check the address book. Here is the exception....   See the end of this message for details on invoking just-in-time (JIT) debugging instead of this dialog box.   ************** Exception Text...
AnswerRe: It's not workingmemberteleolog3 Jul '06 - 7:33 
me either......     Any idea from author ??
AnswerRe: It's not workingmemberH. S. Masud3 Jul '06 - 23:24 
No. The author did not replied. I think Gmail has changed their protocol. So, it will not work.   Hasan Shahriar Masud Senior Software Engineer Kaz Software limited Dhaka, Bangladesh URL: http://www.hsmasud.com E-Mail: info@hsmasud.com
GeneralVery Good,But.....memberTrance Junkie14 Aug '05 - 22:22 
This is a very good idea thanks,but is it possible to do this with yahoo it would b great. Thanks non the less
GeneralGmail login parser changed sometime early Feb 2005memberZhefu Zhang18 Feb '05 - 13:38 
Now, the GmailAdaptor.cs Line 231 got to be changed from   string loginPostData = "continue=" + System.Web.HttpUtility.UrlDecode(GOOGLE_LOGIN_URL) + "%2Fgmail&service=mail" + "&Email=" + this._session.Username + "&Passwd=" + this._session.Password + "&null=Sign+in";   into sth...
GeneralRe: Gmail login parser changed sometime early Feb 2005memberjsanjosemgmail.com26 May '05 - 2:18 
I modified the code as you suggest, but still can't connect. Any ideas?   Thank you.
GeneralRe: Gmail login parser changed sometime early Feb 2005memberZhefu Zhang26 May '05 - 6:15 
It may have changed again, use a sniff to see that http context the browser send out.
GeneralRe: Gmail login parser changed sometime early Feb 2005memberArunag16 Feb '06 - 22:02 
Hi   Can you tell me how to configure this sniff or where to get such a one?   Rgds Arunag
GeneralActive discussion thread elsewheresussAnonymous3 Nov '04 - 19:29 
The API is up to 0.61 (still has some bugs), and active(?) discussion can be found at:   http://groups-beta.google.com/group/GmailAgent[^]   Cheers!
GeneralBEWARE OF SCAM!!memberTom Archer13 Sep '04 - 15:55 
The article refers to a utility called "Pop Goes the Weasel". On that site, the author of the code states that he/she would appreciate a donation for his/her hard work and in return will give the donator the source code. As I have an affinity for people that freely give their time and talents in...
GeneralRe: BEWARE OF SCAM!!memberChristian Graus13 Sep '04 - 16:26 
Did you mean 'Pop goes the GMail' ?   Christian   I have drunk the cool-aid and found it wan and bitter. - Chris Maunder
GeneralRe: BEWARE OF SCAM!!memberTom Archer13 Sep '04 - 16:43 
Freudian slip   Cheers, Tom Archer "Use what talents you possess. The woods would be very silent if no birds sang there except those that sang best." - William Blake * Inside C# -Second Edition * Visual C++.NET Bible * Extending MFC Applications with the .NET Framework
GeneralRe: BEWARE OF SCAM!!memberZhefu Zhang18 Feb '05 - 12:42 
Thanks, Tom. Otherwise I will be the Nth victim of that guy
GeneralDoesn't appear to workmemberTom Archer3 Sep '04 - 16:32 
I installed the agent, specified my gmail account info, sent a test email from outlook and never got a notification of the email.   Cheers, Tom Archer "Use what talents you possess. The woods would be very silent if no birds sang there except those that sang best." - William Blake *...
GeneralRe: Doesn't appear to workmembereggie53 Sep '04 - 18:18 
I believe Google recently changed their protocol, to prevent third party access.   /\ |_ E X E GG
GeneralRe: Doesn't appear to workmemberTom Archer3 Sep '04 - 18:46 
Actually, Catalin's version (also on this site) works. I found that article after trying this. Thanks though.   Cheers, Tom Archer "Use what talents you possess. The woods would be very silent if no birds sang there except those that sang best." - William Blake * Inside C# -Second...
GeneralRe: Doesn't appear to workmembereggie53 Sep '04 - 19:47 
Oh... and on the subject, google made one too if you didn't hear about it.   /\ |_ E X E GG
GeneralRe: Doesn't appear to workmemberTom Archer4 Sep '04 - 3:27 
Actually we just got our accounts so I'm quite new to this. Thanks for pointing it out! Yet another API to play around and learn   Cheers, Tom Archer "Use what talents you possess. The woods would be very silent if no birds sang there except those that sang best." - William Blake *...
QuestionFull Message Text?memberAmberite0029 Aug '04 - 11:58 
Hi, great API! Great Work!   I was just wondering... For an individual thread, the API allows for getting everything EXCEPT the entire thread body text (a snippet is available, but that's all)... Is there any way for the API to retrieve the entire body text?   Thanks!  ...
General21 MB of RAM in idle state....membercamelopardis4 Aug '04 - 21:04 
OMG!
GeneralRe: 21 MB of RAM in idle state....memberElNoNo10 Aug '04 - 10:14 
Heh that's MS.NET my friend ^^
GeneralRe: 21 MB of RAM in idle state....sussAnonymous20 Aug '04 - 14:09 
This is a common misconception... when the .Net Framework is loaded, it pushes the "minimum working set" for your application out to around 20-30 megs. Your application is not actually using this much memory, but it *has* (during startup) and as a result Windows sets that much memory aside for...
GeneralRe: 21 MB of RAM in idle state....memberEric Van de Kerckhove9 Feb '06 - 10:06 
Thanks for this info! I didn't know this   Eric Van de Kerckhove, C# novice
GeneralGreat APIsussNalokeiki23 Jul '04 - 13:20 
So far I think Gmail is pretty nice. It's very basic in nature and I enjoy the discussion thread type inbox. This API is pretty sweet as well. I'm hoping in the future Gmail releases information for use in outlook.     Sean
GeneralProblems with signing inmemberKirill Yatsenko16 Jul '04 - 22:26 
I'd like to get GMAIL account but i was not able? Does anyone know how to get it?   KTB wrote that
GeneralRe: Problems with signing inmemberS.K Vasantha Mohan20 Jul '04 - 11:55 
Gmail is in a limited test period and is only available to a small number of people who are helping test and improve the service before it is made more widely available. If you haven't been invited to test Gmail, you would not be able to have a Gmail account of yours.
GeneralRe: Problems with signing inmembershahabdhk1 Dec '06 - 3:59 
you must be invited by some one, i have few invitations left...mail me if u need it...i mean gmail account shahabdhk@gmail.com   bye
GeneralRe: Problems with signing inmemberKirill Yatsenko1 Dec '06 - 4:08 
Wow, I couldn't even imagine that someone would read such an old post. Thanks, Shahabdhk, but I have it for two years already   Thanks, any way! Cheers!   KTB
GeneralNot working with Proxymembermarksteve_7414 Jul '04 - 1:00 
I also have proxy ... it is not working with it.   Mark My Site :
GeneralRe: Not working with Proxymembermaharsoft11 Mar '05 - 0:17 
Me too....with or without proxy
QuestionWhat does Google think about that?memberGreg Ennis13 Jul '04 - 3:39 
I have to believe that Google does not like people reverse engineering their API and developing stuff like this. What you have so far is fine, but they really don't want people using tons of 1GB email accounts for sharing files/music/warez etc. without even viewing their advertisements.  ...
AnswerRe: What does Google think about that?memberTomas Gunnarsson14 Jul '04 - 1:17 
I personally doubt that google would send their lawyers for this. There are quite a few packages out there, including open source code, that do the same for Hotmail and Yahoo! that this article does for Gmail and so far I haven't heard of lawsuits.   What I would rather expect is, as you...
GeneralRe: What does Google think about that?memberGreg Ennis14 Jul '04 - 1:33 
I didn't mean for that to sound threatening, you are right, sorry about that. I have no connection to Google whatsoever.   The difference between Gmail and the other services you mention are that Gmail allows 1GB of storage. The other services are basically useless for storing file...
GeneralRe: What does Google think about that?memberhumbal1 Aug '04 - 20:54 
Hey Mr.Greg Ennis and Mr.Tomas Gunnarsson, Lets just say Johnvey Hwang has done a great Job.   Johnvey Hwang your article was INTERESTING and INFORMATIVE. Probably because its the new thing and the hype of gmail is on.   Your article also answered questions alot of gmailers had...
GeneralRe: What does Google think about that?memberTomas Gunnarsson31 Aug '04 - 6:48 
thank you! Its always nice to meet a fan
GeneralRe: What does Google think about that?membereRRaTuM2 Jun '05 - 6:47 
hi, Even if it's a bit late, I would like to notice that: - CodeProject® is not a commercial site, and thus all the code exposed in it, is just for fun (The fun of CODING) - The Code you see here shows how to use APIs, winforms controls, etc. -...
GeneralSourceForgesussAnonymous9 Jul '04 - 3:23 
Are you planning to add this to Sourceforge?
GeneralRe: SourceForgemembersmallguy17 Jul '04 - 1:50 
I'd add it to gotdotnet workspaces, atleast then you get source control that works with visual studio.net. Tortoise cvs is painful with vs.net, although sourceforge does have a large user base of course
GeneralBug in the web requestsussigormoochnick8 Jul '04 - 10:15 
In the GmailAdapter.cs on line 223: all the concatenated parts should be UrlEncoded -   string loginPostData = "continue=" + HttpUtility.UrlEncode(GOOGLE_LOGIN_URL) + "%2Fgmail&service=mail" + "&Email=" + HttpUtility.UrlEncode(this._session.Username) + "&Passwd=" +...
GeneralCurrent Project Home PagesussJohnvey Hwang7 Jul '04 - 7:25 
You can always find the lastest version of this project at: http://johnvey.com/features/gmailapi/   Discussion about this project is over at: http://groups-beta.google.com/group/GmailAgent/   - J

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 7 Jul 2004
Article Copyright 2004 by Johnvey Hwang
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid