Posts Tagged ‘Gmail’

Get Google contacts

Friday, April 13th, 2012

Although neither POP3 nor IMAP protocol allows retrieving the list of users contacts, it is possible to use Google API for that.

As long as you are using OAuth to access Gmail, Mail.dll email component allows you to easy download Gmail contacts of a particular user.

// C#

GmailOAuth oauth = new GmailOAuth(_consumerKey, _consumerSecret);

List<GoogleScope> scopes = new List<GoogleScope>
    {
        GoogleScope.EmailAddressScope,
        GoogleScope.ContactsScope
    };

string authUrl = oauth.GetAuthorizationUrl("http://localhost:64119/", scopes);

// ASP.NET client:
// Save oauth in permanent storage:
// Cache[oauth.RequestToken.Token] = oauth;

// Windows client:
Process.Start(url);

// ASP.NET client:
// Response.Redirect(url);

// Windows client with url:
string rawReturnUrl = Console.ReadLine();
ReturnUrl returnUrl = new ReturnUrl(rawReturnUrl);
oauth.GetAccessToken(returnUrl.OAuthVerifier);

// Windows client with verification code (oob):
// string oauthVerifier = HttpUtility.UrlDecode(Console.ReadLine());
// oauth.GetAccessToken(oauthVerifier);

// ASP.NET client:
// ReturnUrl returnUrl = new ReturnUrl(Request.RawUrl);
// Retrieve oauth from permanent storage:
// GmailOAuth oauth = Cache[returnUrl.OAuthToken]
// oauth.GetAccessToken(returnUrl.OAuthVerifier);

GoogleApi google = new GoogleApi(oauth.ConsumerToken, oauth.AccessToken);

XmlDocument contacts = google.GetContacts();

XmlNamespaceManager nsmgr = new XmlNamespaceManager(contacts.NameTable);
nsmgr.AddNamespace("gd", "http://schemas.google.com/g/2005");
nsmgr.AddNamespace("a", "http://www.w3.org/2005/Atom");

foreach (XmlNode contact in contacts.GetElementsByTagName("entry"))
{
    XmlNode title = contact.SelectSingleNode("a:title", nsmgr);
    XmlNode email = contact.SelectSingleNode("gd:email", nsmgr);

    Console.WriteLine("{0}: {1}",
        title.InnerText,
        email.Attributes["address"].Value);
}

oauth.RevokeToken(oauth.AccessToken.Token);
' VB.NET

Dim oauth As New GmailOAuth(_consumerKey, _consumerSecret)

Dim scopes As New List(Of GoogleScope)() With { _
	GoogleScope.EmailAddressScope, _
	GoogleScope.ContactsScope _
}
Dim authUrl As String = oauth.GetAuthorizationUrl("http://localhost:64119/", scopes)

' ASP.NET client:
' Save oauth in permanent storage:
' Cache[oauth.RequestToken.Token] = oauth;

' Windows client:
Process.Start(url)

' ASP.NET client:
' Response.Redirect(url)

' Windows client with url:
Dim rawReturnUrl As String = Console.ReadLine()
Dim returnUrl As New ReturnUrl(rawReturnUrl)
oauth.GetAccessToken(returnUrl.OAuthVerifier)

' Windows client with verification code (oob):
' Dim oauthVerifier As String = HttpUtility.UrlDecode(Console.ReadLine())
' oauth.GetAccessToken(oauthVerifier)

' ASP.NET client:
' Dim returnUrl As New ReturnUrl(Request.RawUrl)
' Retrive oauth from permanent storage:
' Dim oauth As GmailOAuth = Cache(returnUrl.OAuthToken)
' oauth.GetAccessToken(returnUrl.OAuthVerifier)

Dim google As New GoogleApi(oauth.ConsumerToken, oauth.AccessToken)
Dim contacts As XmlDocument = google.GetContacts()

Dim nsmgr As New XmlNamespaceManager(contacts.NameTable)
nsmgr.AddNamespace("gd", "http://schemas.google.com/g/2005")
nsmgr.AddNamespace("a", "http://www.w3.org/2005/Atom")

For Each contact As XmlNode In contacts.GetElementsByTagName("entry")
	Dim title As XmlNode = contact.SelectSingleNode("a:title", nsmgr)
	Dim email As XmlNode = contact.SelectSingleNode("gd:email", nsmgr)
	Console.WriteLine("{0}: {1}", _
            title.InnerText, _
            email.Attributes("address").Value)
Next

oauth.RevokeToken(oauth.AccessToken.Token)

Label message with Gmail system label (e.g. Starred)

Saturday, March 31st, 2012

If you want to use user-defined label please read label message with user defined label.

There are two ways of labeling message with Gmail system label (e.g. Starred)

Imap.GmailLabelMessageByUID method

GmailLabelMessageByUID method uses Gmail’s X-GM-LABELS extension to the IMAP protocol. You need to provide a folder flag name for it to work correctly e.g. @”\Starred”.

You can use FolderFlag class static properties to get common flags:
FolderFlag.XImportant, FolderFlag.XSpam, FolderFlag.XStarred.

// C#

using (Imap imap = new Imap())
{
    imap.ConnectSSL("imap.gmail.com");
    imap.Login("pat@gmail.com", "password");

    imap.SelectInbox();
    long last = imap.GetAll().Last();

    imap.GmailLabelMessageByUID(last, FolderFlag.XStarred.Name);

    imap.Close();
}
' VB.NET

Using imap As New Imap()
    imap.ConnectSSL("imap.gmail.com")
    imap.Login("pat@gmail.com", "password")

    imap.SelectInbox()
    Dim last As Long = imap.GetAll().Last()

    imap.GmailLabelMessageByUID(last, FolderFlag.XStarred.Name)

    imap.Close()
End Using

Imap.CopyByUID method

The second method basis on the fact that Gmail treats labels as regular IMAP folders.
You just need to know correct folder name and copy the message to this folder.

You can use CommonFolders class to get common folders:

// C#

using (Imap imap = new Imap())
{
    imap.ConnectSSL("imap.gmail.com");
    imap.Login("pat@gmail.com", "password");

    List<FolderInfo> folders = imap.GetFolders();

    imap.SelectInbox();
    long last = imap.GetAll().Last();

    imap.CopyByUID(last, new CommonFolders(folders).Starred);

    imap.Close();
}
' VB.NET

Using imap As New Imap()
    imap.ConnectSSL("imap.gmail.com")
    imap.Login("pat@gmail.com", "password")

    Dim folders As List(Of FolderInfo) = imap.GetFolders()

    imap.SelectInbox()
    Dim last As Long = imap.GetAll().Last()

    imap.CopyByUID(last, New CommonFolders(folders).Starred)

    imap.Close()
End Using

List all Gmail labels

Friday, March 30th, 2012

Gmail treats labels as folders for the purposes of IMAP.

As such, labels can be modified using the standard IMAP commands, CreateFolder, RenameFolder, and DeleteFolder, that act on folders.

System labels, which are labels created by Gmail, are reserved and prefixed by “[Gmail]” or “[GoogleMail]” in the list of labels.

// C#

using (Imap imap = new Imap())
{
    imap.ConnectSSL("imap.gmail.com");
    imap.Login("pat@gmail.com", "password");

    List<FolderInfo> folders = imap.GetFolders();
    List<FolderInfo> system = folders.FindAll(x => x.Name.StartsWith("[Gmail]"));
    List<FolderInfo> user = folders.FindAll(x => !x.Name.StartsWith("[Gmail]"));

    Console.WriteLine("System labels:");
    system.ForEach(x => Console.WriteLine(x.Name));
    Console.WriteLine();
    Console.WriteLine("User labels:");
    user.ForEach(x => Console.WriteLine(x.Name));

    imap.Close();
}
' VB.NET

Using imap As New Imap()
    imap.ConnectSSL("imap.gmail.com")
    imap.Login("pat@gmail.com", "password")

    Dim folders As List(Of FolderInfo) = imap.GetFolders()
    Dim system As List(Of FolderInfo) =
        folders.FindAll(Function(x) x.Name.StartsWith("[Gmail]"))
    Dim user As List(Of FolderInfo) =
        folders.FindAll(Function(x) Not x.Name.StartsWith("[Gmail]"))

    Console.WriteLine("System labels:")
    system.ForEach(Function(x) Console.WriteLine(x.Name))
    Console.WriteLine()
    Console.WriteLine("User labels:")
    user.ForEach(Function(x) Console.WriteLine(x.Name))

    imap.Close()
End Using

Here is the output:


System labels:
[Gmail]
[Gmail]/All Mail
[Gmail]/Drafts
[Gmail]/Sent Mail
[Gmail]/Spam
[Gmail]/Starred
[Gmail]/Trash


User labels:
my label
my label/nested
my second label

Download unseen emails from Gmail using IMAP video

Wednesday, February 1st, 2012

In this video you’ll learn how to:

  • Create new application that references Mail.dll IMAP component.
  • Configure Gmail to allow IMAP access.
  • Connect and login to Gmail using SSL secured channel.
  • Search and download unseen emails.
  • Parse downloaded email messages.
  • and finally access most common email properties like subject, sender, attachments.

Enjoy:

Archive email in Gmail

Friday, January 6th, 2012

First remember to enable IMAP in Gmail.

You need to use DeleteMessageByUID method. Messages will be still available in All Mail folder.

// C#

using(Imap imap = new Imap())
{
	imap.ConnectSSL("imap.gmail.com");
	imap.Login("user", "password");

	// Find all emails we want to delete
	imap.SelectInbox();
	List<long> uids = imap.Search(
		Expression.Subject("email to archive"));

	imap.DeleteMessageByUID(uids);

	imap.Close();
}
' VB.NET

Using imap As New Imap()
	imap.ConnectSSL("imap.gmail.com")
	imap.Login("user@gmail.com", "password")

	' Find all emails we want to delete
	imap.SelectInbox()
	Dim uids As List(Of Long) = imap.Search(_
		Expression.Subject("email to archive"))

	imap.DeleteMessageByUID(uids)

	imap.Close()
End Using