Click here to Skip to main content
Click here to Skip to main content

IMAP Client library using C#

By , 20 Sep 2012
 

Introduction

The Internet Message Access Protocol (IMAP) allows a client to access and manipulate electronic mail messages on a server. It includes operations for creating, deleting, and renaming mailboxes; checking for new messages; permanently removing messages; setting and clearing flags; [RFC-822] and [MIME-IMB] parsing; searching; and selective fetching of message attributes, texts, and portions thereof. For more information: here.

I have written an IMAP client library which allows basic functionalities like login, select/examine folder, search messages, fetch message (Header, Body), get storage quota, and logout.

This is my first application developed in C#, so don't expect too much in terms of efficiency. It demonstrates the use of sockets, XML writer, and user defined exception handling. Please feel free to modify and use this code.

The attached zip file contains three directories.

IMAP Library: It contains three source files.

  • ImapBase.cs: contains the IMAP commands related to string, and socket related functionality.
  • ImapException.cs: defines the user defined IMAP related error messages.
  • Imap.cs: IMAP client library functions. It has the following public functions:
    • Login: Login to IMAP server. It requires IMAP hostname, port, username, and password.
      <COMMAND_PREFIX> LOGIN <USERID> <PASSWORD>\r\n
    • Logout: Logout and close the socket.
      <COMMAND_PREFIX> LOGOUT\r\n
    • SelectFolder: It selects the folder. It requires folder name as parameter.
      <COMMAND_PREFIX> SELECT <FOLDER>\r\n
    • ExamineFolder: It is similar to SelectFolder, but it does examine.
      <COMMAND_PREFIX> EXAMINE <FOLDER>\r\n
    • GetQuota: Get the quota of the mailbox.
      <COMMAND_PREFIX> GETQUOTAROOT <FOLDER>\r\n
    • SearchMessage: You can search the messages. It will return the UID of messages. E.g., From rjoshi.
      <COMMAND_PREFIX> SEARCH <SEARCH STRING>\r\n
    • FetchMessage: It retrieves the complete message with attachments and writes into an XML file. The XML file will be generated in your current directory with file name as <MessageUID>.xml. You need to pass the XmlTextWriter object, message UID, and flag to fetch body.
      <COMMAND_PREFIX> UID FETCH  <MSG UID> BODY[HEADER]
    • FetchPartBody: Fetch the body for a specific part. It requires message UID, part number as parameter.
    • FetchPartHeader: Fetch the header of message.

Documentation: HTML Documentation for IMAP Library generated using Visual Studio .NET.

IMAP Library test program: The IMAP test program allows users to test the following functionalities.

  • Login
  • Select/Examine folder
  • Search
  • Fetch Message
  • Get Quota
  • Logout
  • Delete Message
  • Mark Message UnRead 
  • Move Message

   
 

Update: Added support for

  1. SSL Connection and verified with gmail
  2. Copy Message
  3. Move Message
  4. Delete Message 
  5. Mark Message Unread  
Please don't forget to Vote if you like this library !!

License

This article, along with any associated source code and files, is licensed under The Mozilla Public License 1.1 (MPL 1.1)

About the Author

Rohit Joshi
Software Developer
United States United States
Member
Rohit Joshi is a software engineer working for a telecom company in USA. He has development expirience using C, C++ ,C#, VoiceXML, ASR, IMAP, LDAP, HTTP, SIP, H323 on unix/linux and platforms.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberImpenneteri22 Mar '13 - 10:01 
I'll really learn from this. Kudos man!
QuestionUnable to find the Message Body while fetching the mailmemberramya.km29 Jan '13 - 22:03 
Hi Rohit,
 
Awesome article,
 
I am unable to find the Message body while fetching the email based on the message UID.
Kindly do let me know whether message body is in encrypted format or it is not fetching the same.
 
Message UID[]:174
Fetch Body:[false]true
IMAP004 UID FETCH 174 BODY[HEADER]
* 109 FETCH (BODY[HEADER] {1264}
MIME-Version: 1.0
Received: from SIXPRD0211HT002.apcprd02.prod.outlook.com (10.255.38.165) by
HKXPRD0210HT002.apcprd02.prod.outlook.com (10.255.5.165) with Microsoft SMTP
Server (TLS) id 14.16.257.4; Thu, 17 Jan 2013 12:50:20 +0000
Received: from SIXPRD0211MB443.apcprd02.prod.outlook.com ([169.254.3.223]) by
SIXPRD0211HT002.apcprd02.prod.outlook.com ([10.255.38.165]) with mapi id
14.16.0257.004; Thu, 17 Jan 2013 12:50:20 +0000
From: sdfsdf
To: SDFsdf
CC: sdfsdfsdf
Subject: Regarding Call
Thread-Topic: Regarding Call
Thread-Index: Ac30sTTbHCu6LpNPTMqblRRGClmd/Q==
Date: Thu, 17 Jan 2013 12:50:19 +0000
Message-ID:

Accept-Language: en-US
Content-Language: en-US
X-MS-Exchange-Organization-AuthAs: Internal
X-MS-Exchange-Organization-AuthMechanism: 04
X-MS-Exchange-Organization-AuthSource:
SIXPRD0211HT002.apcprd02.prod.outlook.com
X-MS-Has-Attach:
X-MS-Exchange-Organization-SCL: -1
X-MS-TNEF-Correlator:
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
 
UID 174 FLAGS (\Seen))
IMAP004 OK FETCH completed.
 
IMAP005 UID FETCH 174 BODYSTRUCTURE
* 109 FETCH (BODYSTRUCTURE ("text" "html" ("charset" "iso-8859-1") NIL NIL "quot
ed-printable" 3342 79 NIL NIL "en-US" NIL) UID 174)
IMAP005 OK FETCH completed.
QuestionProblem with attachment fileNamememberMember 96878062 Jan '13 - 2:59 
Hello Rohit
Is InterIMAP Library project always in course ?
It's work well but for most of the mail, attachment file name is not the real one but things like 0FB6C3935BF49BEDB41EA27EBE751@eurprd06.prod.outlook.com.
Did you do correction around that ?
Best regards
AnswerRe: Problem with attachment fileNamememberRohit Joshi24 Jan '13 - 4:18 
No, someone fork from this and created InterImap but don't know the state.
If you have any issues, do let me know and I can provide the fix.
QuestionMissing parameter in Restore FuncmemberIkarus7631 Dec '12 - 0:28 
Hi,
the re-login in Restore(bool) is done without the ssl flag. I assume the line should look like:
 
Login(m_sHost, m_nPort, m_sUserId, m_sPassword, m_bSSLEnabled);
 
regards,
Michael
AnswerRe: Missing parameter in Restore FuncmemberRohit Joshi24 Jan '13 - 4:15 
Thanks. I will fix it and upload new version.
QuestionGMail problem, only for GoogleApp accountmemberroberto.roncato11 Dec '12 - 21:24 
Hi, your library goes very well for my account xxxxxx@gmail.com, but if I try with yyyyy@domain.com, hosted by GMail, this doesn't work.
 
If I use the same params in Thunderbird (imap.gmail.com, SSL, port 993) it works
 
Obviusly I have activated the IMAP access on GMail configuration panel.
 
Someone can help me?
Thanks!
AnswerRe: GMail problem, only for GoogleApp accountmemberroberto.roncato11 Dec '12 - 21:38 
I resolve...
The problem was the password, something like: (Aaaaa0000)
 
I change the password, and all is fine...
GeneralRe: GMail problem, only for GoogleApp accountmemberRohit Joshi24 Jan '13 - 4:15 
Great!!
QuestionSearching email subject vluesmemberthetra30 Nov '12 - 3:43 
Hi! I went through Joshi.Utils.Imap.Imap classes...You have done good work. I'm new to this kind of programming and I wondered if it is possible to get the subjectName and mailDate somewhere in those methods. I want to search through emails particularly on subjectfield and email sent date.

Thanking you

With Regards
Sofi
AnswerRe: Searching email subject vlues [modified]memberRohit Joshi30 Nov '12 - 6:30 
If you look at the ImapLibraryTest program, it does allow you to search. Below is the list of search option which does include subject and since/before for the date.
 
http://www.codeproject.com/Messages/4413518/Re-How-to-use-SearchMessage.aspx[^]

modified 3 Dec '12 - 15:17.

GeneralRe: Searching email subject vluesmemberthetra5 Dec '12 - 22:20 
Hi!
Does it function well with webclient - Exchange server 2003. When I tried to login- like "test.Login("imap.nordicpim.com", "110", "xxx@xxxx.com", "xxxx")" I get errorMsg "Failed authenticating the user/password in the IMAP server". I know that username and password is correct.
Thanks
GeneralRe: Searching email subject vluesmemberRohit Joshi24 Jan '13 - 4:17 
Unfortunately, I don't have access to exchange server 2003. If you can send me error details, I can check what's problem.
QuestionHow to use SearchMessagememberChristian A Berczely26 Oct '12 - 7:27 
Can you provide some examples of SearchMessage?
 
Like:
-searching on header and body at the same time
-searching on unread messages only
 
Good work!
AnswerRe: How to use SearchMessagememberRohit Joshi29 Oct '12 - 10:08 
See the below commands supported for IMAP protocol for search
FROM "<mailaddress>"	 Mail from that sender	FROM "user@example.org"
TO "<mailaddress>"	 Mail to that recipient	TO "user@example.org"
SINCE <date>	 Mail received after this date	SINCE 1-Nov-2009
BEFORE <date>	 Mail received before this date	BEFORE 1-Nov-2009
DELETED	 Mails marked as deleted	DELETED
SUBJECT <string>	 Mails containing string in the subject	SUBJECT "Proposal"
BODY <string>	 Mails containing string in the body	BODY "Hello Greg"
NOT <key>	 Mails which do not match the key	NOT FROM "user@example.org"
OR <key1> <key2>	 Mails which match either of key1 or key2	OR FROM "user@example.org" FROM "user2@example.org"

QuestionAdd mail to sent itemsmemberRenoMarseille19 Oct '12 - 23:40 
Hi, verry useful library
I need to save email to sent items box
Someone have some info about append command
 
Thank
QuestionSTORE command failurememberMichael Mak16 Oct '12 - 18:10 
Hi
 
I found this nice library a few days ago. I love its simplicity in achieving such a complicated task!
 
When I tried to issue the STORE command to set the SEEN flag, a read-only error occur.
 
Below was the screen output during my trial:
Warning:* OK Gimap ready for requests from 203.2.94.202 i4if9061028oac.120
Warning:IMAP001 CAPABILITY
Warning:* CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 XYZZY SASL-IR AUTH=XOAUTH AUTH=XOAUTH2
Warning:IMAP001 OK Thats all she wrote! i4if9061028oac.120
Warning:
Warning:IMAP002 LOGIN user@gmail.com thispassword
Warning:* CAPABILITY IMAP4rev1 UNSELECT IDLE NAMESPACE QUOTA ID XLIST CHILDREN X-GM-EXT-1 UIDPLUS COMPRESS=DEFLATE
Warning:IMAP002 OK user@gmail.com Michael Mak authenticated (Success)
Warning:
Warning:IMAP003 EXAMINE INBOX
Warning:* FLAGS (\Answered \Flagged \Draft \Deleted \Seen)
Warning:* OK [PERMANENTFLAGS ()] Flags permitted.
Warning:* OK [UIDVALIDITY 661234706] UIDs valid.
Warning:* 1 EXISTS
Warning:* 0 RECENT
Warning:* OK [UIDNEXT 250] Predicted next UID.
Warning:IMAP003 OK [READ-ONLY] INBOX selected. (Success)
Warning:
Warning:IMAP004 UID SEARCH UNSEEN
Warning:* SEARCH 249
Warning:IMAP004 OK SEARCH completed (Success)
Warning:
Unseen Messages: 1
Warning:IMAP005 UID STORE 249 -FLAGS \SEEN
Warning:IMAP005 NO STORE attempt on READ-ONLY folder (Failure)
Warning:
 
Would there be any mistake I've made?
 
Thnx
 
SMak
AnswerRe: STORE command failurememberRohit Joshi17 Oct '12 - 4:03 
Thanks for the complement!!
 
If you look at the command IMAP003 EXAMINE INBOX which means you are just examining the folder and can't change.
 
Use SELECT instead of EXAMINE and should work fine.
GeneralRe: STORE command failurememberMichael Mak17 Oct '12 - 12:00 
Thnx Rohit.
QuestionFailure bodystructure commandmemberMember 800245416 Oct '12 - 5:44 
i Think I am getting closer and closer to solution on my own I am now getting the following error
 
Failure bodystructure command
 
My Code is
 
Dim oImap As New Imap
 
Dim sHost As String = "imap.gmail.com"
Dim sPort As String = "993"
Dim bSSL As Boolean = True
Dim sUser As String = "ffff"
Dim sPwd As String = "wwwww"
 
oImap.Login(sHost, Convert.ToUInt16(sPort), sUser, sPwd, bSSL)
oImap.SelectFolder("INBOX")
 

Dim str As String
 
Dim saArray As New ArrayList
Dim strSearch(0) As String
strSearch(0) = "1"
 
oImap.SearchMessage(strSearch, False, saArray)
 
For Each str In saArray
    If str.Length > 0 Then
        Dim sFileName As String = str + ".xml"
 
        Dim oXmlWriter As New XmlTextWriter(sFileName, System.Text.Encoding.UTF8)
 
        oXmlWriter.Formatting = Formatting.Indented
        oXmlWriter.WriteStartDocument(True)
        oXmlWriter.WriteStartElement("Message")
        oXmlWriter.WriteAttributeString("UID", str)
        oImap.FetchMessage(str, oXmlWriter, True)
        oXmlWriter.WriteEndElement()
        oXmlWriter.WriteEndDocument()
        oXmlWriter.Flush()
        oXmlWriter.Close()
    End If
Next

QuestionFailure fetching message from IMAP folder/mailbox. BODY[HEADER]memberMember 800245416 Oct '12 - 5:30 
I am getting there error Failure fetching message from IMAP folder/mailbox. BODY[HEADER]
 
my code is as below
 
Dim oImap As New Imap
 
Dim sHost As String = "imap.gmail.com"
Dim sPort As String = "993"
Dim bSSL As Boolean = True
Dim sUser As String = "xcxvxvx"
Dim sPwd As String = "rtrtrtrtr"
 
oImap.Login(sHost, Convert.ToUInt16(sPort), sUser, sPwd, bSSL)
oImap.SelectFolder("INBOX")
 

Dim i As Integer
Dim saArray As New ArrayList()
Dim strSearch(0) As String
strSearch(0) = "1"
 
oImap.SearchMessage(strSearch, False, saArray)
 
For i = 0 To saArray.Count - 1
 
    Dim sFileName As String = saArray(i) + ".xml"
 
    Dim oXmlWriter As New XmlTextWriter(sFileName, System.Text.Encoding.UTF8)
 
    oXmlWriter.Formatting = Formatting.Indented
    oXmlWriter.WriteStartDocument(True)
    oXmlWriter.WriteStartElement("Message")
    oXmlWriter.WriteAttributeString("UID", saArray(i))
    oImap.FetchMessage(saArray(i), oXmlWriter, True)
    oXmlWriter.WriteEndElement()
    oXmlWriter.WriteEndDocument()
    oXmlWriter.Flush()
    oXmlWriter.Close()
Next i

QuestionFailure searching IMAP with the given criteria. IMAP004 BAD Could not parse commandmemberMember 800245416 Oct '12 - 5:24 
this is a sample of my code
 

Sub Main()
 
    Dim oImap As New Imap
 
    Dim sHost As String = "imap.gmail.com"
    Dim sPort As String = "993"
    Dim bSSL As Boolean = True
    Dim sUser As String = "xx"
    Dim sPwd As String = "xxxxxxx"
 
    oImap.Login(sHost, Convert.ToUInt16(sPort), sUser, sPwd, bSSL)
    oImap.SelectFolder("INBOX")
 

    Dim i As Integer
    Dim saArray As New ArrayList()
    Dim strSearch(0) As String
    strSearch(0) = "trustaldo"
 
    oImap.SearchMessage(strSearch, False, saArray)
 
    For i = 0 To saArray.Count - 1
 
        Dim sFileName As String = saArray(i) + ".xml"
 
        Dim oXmlWriter As New XmlTextWriter(sFileName, System.Text.Encoding.UTF8)
 
        oXmlWriter.Formatting = Formatting.Indented
        oXmlWriter.WriteStartDocument(True)
        oXmlWriter.WriteStartElement("Message")
        oXmlWriter.WriteAttributeString("UID", saArray(i))
        oImap.FetchMessage(saArray(i), oXmlWriter, True)
        oXmlWriter.WriteEndElement()
        oXmlWriter.WriteEndDocument()
        oXmlWriter.Flush()
        oXmlWriter.Close()
    Next i
 

End Sub
 

 

 
Failure searching IMAP with the given criteria. IMAP004 BAD Could not parse command
QuestionCan't obtain email bodymembereladfrn16 Oct '12 - 4:46 
Hello,
 
I am trying to fetch a simple email from Gmail. I am using
oImap.FetchMessage(sUid, oXmlWriter, true);
with the proper uid but the email is returned without its body.
This is the email body (copied and pasted from the email itself) :
"Your New Password is: ######
Your Customer Number is: 507879072
Web Site: http://www.012Bill.Net"
 
And the email message in my app is :
 



e@gmail.com
by 10.58.190.194 with SMTP id gs246vec; Sat, 1 Sep 201201:47:31 -0700 (PDT)
by 10.180.97.33 with SMTP id dx1mr019wib.18.134651388; Sat,01 Sep 2012 01:47:31 -0700 (PDT)
<Info@012.net>
from mtaout22.012.net.il (mtaout22.012.net.il. [80.179.55.172]) bymx.google.com with ESMTP id r49si9250693wed.63.2012.09.01.01.47.30; Sat, 01Sep 2012 01:47:31 -0700 (PDT)
neutral (google.com: 80.179.55.172 is neither permitted nordenied by best guess record for domain of Info@012.net)client-ip=80.179.55.172;
mx.google.com; spf=neutral (google.com: 80.179.55.172is neither permitted nor denied by best guess record for domain ofInfo@012.net) smtp.mail=Info@012.net
from conversion-daemon.a-mtaout22.012.net.il bya-mtaout22.012.net.il (HyperSendmail v2007.08) id<0M9N00I00XDLRL00@a-mtaout22.012.net.il> for elain@gmail.com; Sat, 01Sep 2012 11:46:03 +0300 (IDT)
from webapp ([80.179.32.81]) by a-mtaout22.012.net.il (HyperSendmailv2007.08) with ESMTP id <0M9N00IPFXOJAE80@a-mtaout22.012.net.il> forelaklin@gmail.com; Sat, 01 Sep 2012 11:46:03 +0300 (IDT)
Sat, 01 Sep 2012 11:47:11 +0300
012 <Info@012.net>
New password from 012 Bill
elanklin@gmail.com
<0M9N00IQ2XORAE80@a-mtaout22.012.net.il>
1.0
text/html; charset=us-ascii
quoted-printable

TEXT/HTML; CHARSET="us-ascii"
QUOTED-PRINTABLE
223



 
Can you please help?
 
Thanks a lot and great job!!
Elad
GeneralMessage Removedmemberrk.tedlapu8 Oct '12 - 2:19 
Message Removed
GeneralRe: My vote of 4memberRohit Joshi8 Oct '12 - 3:44 
What this a complement by reducing the one star Smile | :)
 
Thanks!!

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130516.1 | Last Updated 20 Sep 2012
Article Copyright 2004 by Rohit Joshi
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid