Posted by: kevinthant | July 11, 2009

Coding IMAP email access using ASP.NET(C#)

At my current work (internship at web development center, Bucknell University), I have a project to implement widgets for snapshot view of most recent emails from popular email services such as Gmail, Yahoo, Hotmail or even any generic IMAP email account. The platform we use is ASP.NET and so I have to come up with a solution to access IMAP email server using C#.

First, there seems to be no native support for IMAP protocol in C# or ASP.NET, unlike in PHP which has IMAP library. So, the solution can be implementing IMAP by yourself from scratch. For that, you might have to digg into TcpClient and socket programming and of course, learn more about commands in IMAP protocol. I think that is too much work for the sake of time budget and started looking for 3rd party libraries for IMAP protocol in ASP.NET. I found a few and some of them are commercial (you have to buy to use their library) and some are free. Anyhow, I found a free and working IMAP library.

The URL for downloading the library is here: http://www.codeproject.com/KB/IP/imaplibrary.aspx.

Now, I would like share how to access an IMAP server using the library.

oImap = new Imap();
oImap.SelectFolder(”INBOX”);
oImap.Login(”imap.gmail.com”, “username@gmail.com”, “password”, true); //last parameter is to use SSL to connect

oImap.SelectFolder(”INBOX”); // select the folder INBOX to see messages

// After logging in, we can now pull the messages and you will a list of message IDs (whole number)

ArrayList msglist = new ArrayList();

string[] saSearchData = new String[1];

saSearchData[0] = “all”; //this is bascially search criteria for fetching messages and in this case it is going to fetch all messsages. Flags can be unseen, seen, answered etc..

//last parameter msglist is passed by reference, after the function it will be populated with message IDs

oImap.SearchMessage(saSearchData, false, msglist);

//Now, let’s read the message header or body of the latest 10 messages.

int limit = 10;

int count = 0;

while (count < limit && count < msglist.Count)

{

string UID = msglist[msglist.Count - (count + 1)].ToString();

MemoryStream stm = new MemoryStream(); //using a memory stream buffer for XmlTextWrite to write

XmlTextWriter oXmlWriter = new XmlTextWriter(stm, System.Text.Encoding.UTF8);

oXmlWriter.Formatting = Formatting.Indented;

oXmlWriter.WriteStartDocument(true);

oXmlWriter.WriteStartElement(”Message”);

oXmlWriter.WriteAttributeString(”UID”, UID);

try

{

//Call to IMAP library’s API function to fetch message . Last parameter indicate not take include message body

// but only header information. You can set it to true to get full message body

oImap.FetchMessage(UID, oXmlWriter, false);

}

catch (Exception err) { //in case there is error in fetching one of the messages, let’s keep going}

oXmlWriter.WriteEndElement();

oXmlWriter.WriteEndDocument();

oXmlWriter.Flush();

stm.Seek(0, SeekOrigin.Begin); //have to move the offset to zero to read from the beginning of the memory stream

XmlTextReader xr = new XmlTextReader(stm)

XmlDocument xmldoc = new XmlDocument();

xmldoc.Load(xr);

stm.Flush();

xr.Close();

stm.Close();

oXmlWriter.Close();

oXmlWriter = null;

//Now, we can use xmldoc to access the message header or body information.

count++;

}

oImap.Logout();

This code above basically does 3 things.

1. Login to the IMAP server
2. Search messages with flags(such as all, seen, unseen, answered etc..)
3. Go through the list of message ids to retrieve the message header or body inside a loop

You can factorize the code by creating functions to carry out these three activites appropiately. I show the code in one chunk altogether for simple example. Following the example output of the XML file after retrieving a message header. Feel free to leave comments or questions.

xxxx@gmail.com

by 10.229.99.139 with SMTP id u11cs34746qcn; Fri, 10 Jul 200905:36:42 -0700 (PDT)

by 10.140.133.4 with SMTP id g4mr1281659rvd.173.1247229400711; Fri,10 Jul 2009 05:36:40 -0700 (PDT)

<bounce@taggedmail.com>

from sf-mta-122.taggedmail.com (sf-mta-122.taggedmail.com[67.221.174.122]) by mx.google.com with ESMTP id40si1758848pzk.60.2009.07.10.05.36.38; Fri, 10 Jul 2009 05:36:38 -0700 (PDT)

pass (google.com: domain of bounce@taggedmail.com designates67.221.174.122 as permitted sender) client-ip=67.221.174.122;

mx.google.com; spf=pass (google.com: domain ofbounce@taggedmail.com designates 67.221.174.122 as permitted sender)smtp.mail=bounce@taggedmail.com; dkim=pass (test mode)header.i=tagged@taggedmail.com

Fri, 10 Jul 2009 05:36:38 -0700 (PDT)

<4a5735d6.a813f30a.4fb4.3db0SMTPIN_ADDED@mx.google.com>

v=1; a=rsa-sha1; c=relaxed/relaxed; s=mail; d=taggedmail.com;h=Reply-to:From:To:Subject:MIME-Version:List-Unsubscribe:Sender:Content-Type:Content-Transfer-Encoding;i=tagged@taggedmail.com; bh=NEAFxDYFxuzb03smcDJGUdxG6ew=;b=HweNoTqainuL98d9SR2Gqy3GI=

a=rsa-sha1; c=nofws; q=dns; s=mail; d=taggedmail.com;b=lTM+IgxL8o0hRHzSBz4rh0=;

from taggedmail.com (10.15.100.16) by sf-mta-122.taggedmail.com(PowerMTA(TM) v3.2r21) id hasqtc0d9jo3 for <xxxx@gmail.com>; Fri, 10 Jul2009 05:36:38 -0700 (envelope-from <bounce@taggedmail.com>)

Tagged <tagged@taggedmail.com>

25652502027

Tagged <tagged@taggedmail.com>

xxxx@gmail.com

Lydia G added you as a friend…

1.0

<http://www.tagged.com/no_more.html?unsem=xxxx%40gmail.com&gt;

Tagged <tagged@taggedmail.com>

text/html; charset=”iso-8859-1″

7bit

TEXT/HTML; CHARSET=”iso-8859-1″

7BIT

6671


Responses

  1. Welcome to the blogging world man… This is a whole lot of computer crap that I don’t understand that I will visit your site when I can.
    I hope you are doing well at your work/internship.

    • Thank you, man!

      • This is interesting.

        I am also currently looking for a free and working IMAP library and found your website. I went to the url in your post:

        http://www.codeproject.com/KB/IP/imaplibrary.aspx

        and downloaded the library from that url. But, I fount the library did not support SSL. For example, the Login(…) function doesn’t have the fourth parameter for SSL.

        I was wondering whether there is a newer link for downloading the updated library? Could you help? Thanks a lot!

        Wendy

      • Hi Wendy,

        I might have tweaked the library code or got the newer version. I don’t remember exactly because I did this project a while ago and currently I don’t have access to the source code for the project which was implemented at previous job.

        Thanks.


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

Categories

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: