Monday, December 11, 2017

Access Google gmail Inbox via 3rd Party Application

Hi folks,

Today, I’m come up with a pretty impressive application, which is allow you to access to your gmail inbox and get the feed about the latest email. This simple application based on Atom Google gmail inbox feed. Before I go to development session, let me explain about the atom, according to Google,
Atom is a system which makes it easy for you to receive, in one place, regular updates from news websites, blogs, and/or Gmail. You can use Atom with an aggregator (also known as a newsreader, feed reader, or RSS/Atom reader) to receive new message alerts.Here we go, this is the way to do it.

Pre Requirements.

In order to access gmail account, you have to allow to access ‘less secure Application’. You can easily do it by referring following screen shots.  

Go to Settings and then click Other Google Account settings

Click Apps with account access

Allow to Access Allow less secure apps

I’ll create a separate class to represent email object, and another separate class to get the data from atom the feed.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GmailReader
{
class Mail
{
public string AuthorName;
public string AuthorEmail;
public string Title;
public string Summary;
public string IssuedDate;
}
}
view raw Mail.cs hosted with ❤ by GitHub

using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Xml;
namespace GmailReader
{
class MailController
{
List<Mail> Mails = new List<Mail>();
private string userName;
private string password;
public MailController(string username, string password)
{
this.userName = username;
this.password = password;
}
public List<Mail> GetAllMails()
{
WebClient objclient = new WebClient();
string response = null;
XmlDocument xdoc = new XmlDocument();
try
{
objclient.Credentials = new NetworkCredential(userName, password);
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>");
xdoc.LoadXml(response);
foreach (XmlNode xmlNode in xdoc.SelectNodes("feed/entry"))
{
Mail mail = new Mail();
mail.AuthorName = xmlNode.SelectSingleNode("author/name").InnerText;
mail.AuthorName = xmlNode.SelectSingleNode("author/email").InnerText;
mail.Title = xmlNode.SelectSingleNode("title").InnerText;
mail.Summary = xmlNode.SelectSingleNode("summary").InnerText;
mail.IssuedDate = xmlNode.SelectSingleNode("issued").InnerText;
Mails.Add(mail);
}
return Mails;
}
catch(System.Exception ex)
{
return null;
}
}
}
}


Get the sample project from GitHub Repository  


Happy Coding,


Best Regards,
Denuwan Himanga