Get unread mail count of Gmail in C#

Following code demonstrate that how to get count of unread mail of Gmail account in C#. Gmail provides link “https://mail.google.com/mail/feed/atom” to access unread mail by user authentication.

Following is code description.
First we declare a structure which will contain information of unread mails –

    struct UnreadMails
    {
        public string From { get; set; }
        public string Subject { get; set; }
        public DateTime MailModify { get; set; }
    }

Now following function will return collection of unread mail using authentication –

        Collection<UnreadMails> GetNewMails()
        {
            WebRequest webGmailRequest = WebRequest.Create(@"https://mail.google.com/mail/feed/atom");
            webGmailRequest.PreAuthenticate = true;

            NetworkCredential loginCredentials = new NetworkCredential(txtUserName.Text.Trim(), txtUserPassword.Text.Trim());
            webGmailRequest.Credentials = loginCredentials;

            WebResponse webGmailResponse = webGmailRequest.GetResponse();
            Stream strmUnreadMailInfo = webGmailResponse.GetResponseStream();

            StringBuilder sbUnreadMailInfo = new StringBuilder(); byte[] buffer = new byte[8192]; int byteCount = 0;

            while ((byteCount = strmUnreadMailInfo.Read(buffer, 0, buffer.Length)) > 0)
                sbUnreadMailInfo.Append(System.Text.Encoding.ASCII.GetString(buffer, 0, byteCount));

            XmlDocument UnreadMailXmlDoc = new XmlDocument();
            UnreadMailXmlDoc.LoadXml(sbUnreadMailInfo.ToString());
            XmlNodeList UnreadMailEntries = UnreadMailXmlDoc.GetElementsByTagName("entry");

            UnreadMails oUnreadMails = new UnreadMails();
            Collection<UnreadMails> clUnreadMails = new Collection<UnreadMails>();

            for (int _i = 0; _i < UnreadMailEntries.Count; ++_i)
            {
                oUnreadMails.Subject = (UnreadMailEntries[_i]["title"]).InnerText;
                oUnreadMails.From = (UnreadMailEntries[_i]["author"])["name"].InnerText + " <" + (UnreadMailEntries[_i]["author"])["email"].InnerText + ">";
                oUnreadMails.MailModify = DateTime.Parse((UnreadMailEntries[_i]["modified"]).InnerText);
                clUnreadMails.Add(oUnreadMails);
            }
            return clUnreadMails;
        }

Now call above function on button click to get count of unread mail. There is also a check in this function that if any unread mail count once then it will not count as new unread mail –

        DateTime LastCheck = DateTime.MinValue;
        private void btnLogin_Click(object sender, EventArgs e)
        {
            int NewUnreadMail = 0;
            DateTime LastUnreadMailDate = DateTime.MinValue;
            Collection<UnreadMails> clUnreadMails = GetNewMails();
            for (int i = 0; i < clUnreadMails.Count; i++)
            {
                if (clUnreadMails[i].MailModify > LastCheck)
                {
                    NewUnreadMail++;
                }
                if (clUnreadMails[i].MailModify > LastUnreadMailDate)
                    LastUnreadMailDate = clUnreadMails[i].MailModify;
            }
            LastCheck = LastUnreadMailDate;
            lblTotalUnreadMailCount.Text = "Total Unread Mail Count -  "+ clUnreadMails.Count.ToString();
            lblNewUnreadMailCount.Text = "New Unread Mail Count -  " + NewUnreadMail.ToString();
        }

Following is a image of UI of form –

Advertisements
Posted in Uncategorized. 8 Comments »

8 Responses to “Get unread mail count of Gmail in C#”

  1. Parvez Says:

    hi ,
    thank for sharing code but in getting same count on totalunread mail & new unread mail………..plz help

    • RAM Says:

      First time you will get same count but after then you will get difference. So you need to save value of “LastCheck” somewhere so that it can be compare with actual last time checked.

      I also not understand following in your code –
      for (int i = 0; i LastCheck)
      {
      NewUnreadMail++;
      }
      if (clUnreadMails[i].MailModify > LastUnreadMailDate)
      LastUnreadMailDate = clUnreadMails[i].MailModify;
      }
      You need to recheck this. Use same as provided in sample.
      Please let me know if it not works or you need any help..

  2. Parvez Says:

    here is my code……..
    using System;
    using System.Configuration;
    using System.Data;
    using System.Linq;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.HtmlControls;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Xml.Linq;
    using System.Collections.ObjectModel;
    using System.Net;
    using System.IO;
    using System.Text;
    using System.Xml;

    public partial class _Default : System.Web.UI.Page
    {
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    struct UnreadMails
    {
    public string From { get; set; }
    public string Subject { get; set; }
    public DateTime MailModify { get; set; }
    }

    Collection GetNewMails()
    {
    WebRequest webGmailRequest = WebRequest.Create(@”https://mail.google.com/mail/feed/atom”);
    webGmailRequest.PreAuthenticate = true;

    NetworkCredential loginCredentials = new NetworkCredential(txtUserName.Text.Trim(), txtUserPassword.Text.Trim());
    webGmailRequest.Credentials = loginCredentials;

    WebResponse webGmailResponse = webGmailRequest.GetResponse();
    Stream strmUnreadMailInfo = webGmailResponse.GetResponseStream();

    StringBuilder sbUnreadMailInfo = new StringBuilder(); byte[] buffer = new byte[8192]; int byteCount = 0;

    while ((byteCount = strmUnreadMailInfo.Read(buffer, 0, buffer.Length)) > 0)
    sbUnreadMailInfo.Append(System.Text.Encoding.ASCII.GetString(buffer, 0, byteCount));

    XmlDocument UnreadMailXmlDoc = new XmlDocument();
    UnreadMailXmlDoc.LoadXml(sbUnreadMailInfo.ToString());
    XmlNodeList UnreadMailEntries = UnreadMailXmlDoc.GetElementsByTagName(“entry”);

    UnreadMails oUnreadMails = new UnreadMails();
    Collection clUnreadMails = new Collection();

    for (int _i = 0; _i < UnreadMailEntries.Count; ++_i)
    {
    oUnreadMails.Subject = (UnreadMailEntries[_i]["title"]).InnerText;
    oUnreadMails.From = (UnreadMailEntries[_i]["author"])["name"].InnerText + " “;
    oUnreadMails.MailModify = DateTime.Parse((UnreadMailEntries[_i][“modified”]).InnerText);
    clUnreadMails.Add(oUnreadMails);
    }
    return clUnreadMails;
    }

    DateTime LastCheck = DateTime.MinValue;

    protected void Button1_Click(object sender, EventArgs e)
    {
    int NewUnreadMail = 0;
    DateTime LastUnreadMailDate = DateTime.MinValue;
    Collection clUnreadMails = GetNewMails();
    for (int i = 0; i LastCheck)
    {
    NewUnreadMail++;
    }
    if (clUnreadMails[i].MailModify > LastUnreadMailDate)
    LastUnreadMailDate = clUnreadMails[i].MailModify;
    }
    LastCheck = LastUnreadMailDate;
    lblTotalUnreadMailCount.Text = “Total Unread Mail Count – ” + clUnreadMails.Count.ToString();
    lblNewUnreadMailCount.Text = “New Unread Mail Count – ” + NewUnreadMail.ToString();

    }
    }

  3. OWEN Says:

    System.Net.WebClient objClient = new System.Net.WebClient();
    XmlNodeList nodelist = default(XmlNodeList);
    XmlNode node = default(XmlNode);
    string response = null;
    XmlDocument xmlDoc = new XmlDocument();

    objClient.Credentials = new System.Net.NetworkCredential(username, password);
    response = Encoding.UTF8.GetString(objClient.DownloadDat(“https://mail.google.com/mail/feed/atom”));

    I am using the code above in C# , I am not getting all the emails from my inbox, the latest about 25 emails are returned, put the https://mail.google.com/mail/feed/atom link into a brower and hit enter, I can see the same thing, the earlier emails are not returned, anyone has a idea?

  4. JItendra Says:

    This code does not show current email. I want show current mail in gridview.
    If you have code of read all email from gmail ,please sent it on my email id.

  5. adf Says:

    i want it for other mail server … can it possible

  6. alli Says:

    how to get number of unread emails with specific subject title?


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: