Create new account I forgot my password    

Build a Simple Gmail Notifier using Windows Forms
Rating: 13 user(s) have rated this article Average rating: 4.8
Posted by: Shoban Kumar, on 3/26/2009, in category "Windows Forms 2.0"
Views: this article has been read 17394 times
Abstract: Google does not have an official Gmail API. Having one would have made it very easy to create a notification application. In this article, I will show you how to exploit the Feed facility of Gmail to build our own Gmail Notifier.

Build a Simple Gmail Notifier using Windows Forms
 
Google does not have an official Gmail API. Having one would have made it very easy to create a notification application. In this article, I will show you how to exploit the Feed facility of Gmail to build our own Gmail Notifier.
Gmail Feed is an useful feature provided by Gmail using which we can subscribe to emails using a Feed reader supporting authentication. You have feeds for your unread mails as well as feeds for your labels.
Before starting to build the application, let’s see how our final product will look like. Below are the screenshots of Login and Notifier screens.

 
GMail Notifier Login
Notifier
Let’s get started.
Step 1: Fire up Visual Studio 2008 and Create a new Windows Application by going to File > New Project > Windows > Windows Form Application
 
Step 2: Add a new form ‘Login form’ to the project by Right Click > Add > New Item. Add 2 textboxes and 1 Button control to the Form. Name the Textboxes as ‘UsernameTextBox’ and ‘PasswordTextBox’ respectively.
 
Step 3: Now go back to Form1 (default form which was added when you created this project) and add 2 labels and a Timer control and name the 2 labels as ‘lblFrom’ andlblMessage’respectively.
 
Step 4: Add a Class file to the project, to declare Global Variables used in the project using Right Click -> Add -> New Item
 
Add the following code to the class file:
 
C#
internal static class GlobalVariables
{
      public static string[] emailFrom = new string[2];
      public static string[] emailMessages = new string[2];
      public static Int16 tempCounter = 0;
      public static Int16 mailCount = 0;
}
 
 
VB.NET
Module GlobalVariables
    Public emailFrom(1), emailMessages(1) As String
    Public tempCounter As Int16 = 0
    Public mailCount As Int16 = 0
End Module
 
Step 5: Double Click the ‘OKbutton in the Login form and type in the following code to the Click event
 
VB.NET
Imports System.Xml
Imports System.Text
 
Public Class LoginForm1
    Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
        Dim objClient As New System.Net.WebClient
        Dim nodelist As XmlNodeList
        Dim node As XmlNode
        Dim response As String
        Dim xmlDoc As New XmlDocument
        Try
 
            objClient.Credentials = New System.Net.NetworkCredential(UsernameTextBox.Text.Trim, PasswordTextBox.Text.Trim)
            response = Encoding.UTF8.GetString(objClient.DownloadData("https://mail.google.com/mail/feed/atom"))
            response = response.Replace("<feed version=""0.3"" xmlns=""http://purl.org/atom/ns#"">", "<feed>")
 
            xmlDoc.LoadXml(response)
            node = xmlDoc.SelectSingleNode("/feed/fullcount")
            mailCount = node.InnerText 'Get the number of unread emails
 
            If mailCount > 0 Then
                ReDim emailFrom(mailCount - 1)
                ReDim emailMessages(mailCount - 1)
                nodelist = xmlDoc.SelectNodes("/feed/entry")
                node = xmlDoc.SelectSingleNode("title")
 
                For Each node In nodelist
                    emailMessages(tempCounter) = node.ChildNodes.Item(0).InnerText
                    emailFrom(tempCounter) = node.ChildNodes.Item(6).ChildNodes(0).InnerText
                    tempCounter += 1
                Next
                tempCounter = 0
            End If
            Me.Hide()
            Form1.Show()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
 
End Class
 
Explanation :  In the code shown above, we first create a new object of ‘Webclient’ class and then request feed from Gmail using the Username and Password as the network credentials. ‘Gmail Feed’ is an useful feature provided by Gmail using which we can subscribe to emails using a Feed reader supporting authentication.
 
Gmail feed is an ATOM feed. Here is an article from MSDN about how we can parse ATOM feeds. But to make our job easier we remove the text <feed version="0.3"mlns="http://purl.org/atom/ns#"> which will help us to parse the response as a normal XML file using ‘XmlDocument’
 
Once the XML message is received, we use the /feed/fullcount to check for any new emails and assign the value to ‘mailCount’. If this value is greater than 0, we store the unread message details in an array.
 
 
Step 6: Now open the Form1 ‘Load’ event and add the folowing code which will position the window at the bottom right corner as shown in the screenshot at the beginning of the article.
 
C#
 
private void Form1_Load(object sender, System.EventArgs e)
{
            Timer1.Enabled = true;
            this.Hide();
            this.ShowInTaskbar = false;
            Left = (SystemInformation.WorkingArea.Size.Width - Size.Width);
            Top = (SystemInformation.WorkingArea.Size.Height - Size.Height);
}
 
VB.NET
 
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Timer1.Enabled = True
        Me.Hide()
        Me.ShowInTaskbar = False
        Left = (SystemInformation.WorkingArea.Size.Width - Size.Width)
        Top = (SystemInformation.WorkingArea.Size.Height - Size.Height)
    End Sub
 
Step 7: Now set the Timer’s interval to 2000 (2 seconds) and add the following code to the ‘Tickevent.
 
C#
 
   private void Timer1_Tick(object sender, System.EventArgs e)
   {
            this.Show();
            if (tempCounter >= mailCount)
            {
                  Timer1.Enabled = false;
                  this.Hide();
            }
            else
            {
                  lblFrom.Text = "From : " + emailFrom(tempCounter);
                  lblMessage.Text = "Subject : " + emailMessages(tempCounter);
                  tempCounter += 1;
            }
 
      }
 
 
VB.NET
 
   Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        Me.Show()
        If tempCounter >= mailCount Then
            Timer1.Enabled = False
            Me.Hide()
        Else
            lblFrom.Text = "From : " & emailFrom(tempCounter)
            lblMessage.Text = "Subject : " & emailMessages(tempCounter)
            tempCounter += 1
        End If
 
    End Sub
 
That’s it. Now run the project and see your Gmail Notifier in action. The source code of this article can be downloaded from here.









Page copy protected against web site content infringement by Copyscape


How would you rate this article?

User Feedback
Comment posted by isidro on Thursday, March 26, 2009 9:25 AM
Nice, very good
Comment posted by Burn on Friday, April 03, 2009 2:49 PM
Why is there no C# example in step 5?  Is it possible to get source for C#
Comment posted by Ken on Thursday, April 23, 2009 2:42 PM
For Step #5 you listed only VB.NET code.
Any chance on the C# equivalent?
Comment posted by SM on Friday, May 15, 2009 6:20 PM
Is there a way to view the message of the email as well as Sender and Subject?
Comment posted by SM on Friday, May 15, 2009 8:47 PM
Never mind, I figured it out:

node.ChildNodes.Item(1).ChildNodes(0).InnerText
Comment posted by D on Saturday, June 06, 2009 12:48 PM
You do not need C# for step 5, it is super simple to rewrite the vb code to C#. If you can't handle that, you should not be coding at all!
Great article!
Comment posted by danny waters on Sunday, July 12, 2009 12:46 PM
I have a question, do you need to re-authenticate every time you want to update your feed ?
Comment posted by M on Tuesday, August 18, 2009 8:59 AM
Getting the folowing error
"The remote server returned an error: (401) Unauthorized."

any clues?
Comment posted by Shoban Kumar on Sunday, August 23, 2009 12:05 PM
Hi M

Make sure your userid and password are correct and try again.

Shoban
Comment posted by John on Sunday, October 18, 2009 4:46 PM
Seams that it didnt work. idk why
Comment posted by cm on Wednesday, October 21, 2009 12:06 AM
Is there a way to view the attachment of the email
Comment posted by dariya on Sunday, November 08, 2009 11:59 PM
this is my code:::
response=Encoding.UTF8.GetString(objClient.DownloadData("https://mail.google.com/mail/feed/atom"));
            response = response.Replace("<feed version='0.3' xmlns=h-*ttp://purl.org/atom/ns#>", "<feed>");
            xmlDocument = new XmlDocument();
            xmlDocument.LoadXml(response);
            //string nodeValue = "";
            node = xmlDocument.SelectSingleNode("/feed/title/text()");

i am getting the node value null.it contains the data then also node value  is returning null.
Comment posted by Justin on Wednesday, June 02, 2010 2:55 PM
By chance, do you know the feed url scheme for a nested label? I cannot find this anywhere.
Comment posted by Kishor Sing on Friday, July 16, 2010 5:36 AM
Very Nice ...


Comment posted by shane on Friday, August 20, 2010 12:16 AM
Hi

could you please post the c# code for step 5 im very new and dont have a clue how to do it myself

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel

NEWSLETTER