Skip to content
227

ImapX – free for use .NET library

ImapX is an modern .NET 2.0 library for management of IMAP folders, supports SSL Connection and different IMAP formats, such as Gmail IMAP, AOL IMAP

Here is simple example of usage:

      ImapX.ImapClient client = new ImapX.ImapClient("imap.gmail.com", 993, true);
      bool result = false;

      result = client.Connection();
      if (result)
        Console.WriteLine("@Connected");

      result = client.LogIn(userName, userPassword);
      if (result)
      {
        Console.WriteLine("@Logged in");
      }
      //Folder Collection
      ImapX.FolderCollection folders = client.Folders;
      //Create folder
      client.CreateFolder("NEW FOLDER", false);
      //Message collection 1st option
      ImapX.MessageCollection messages = client.Folders["INBOX"].Search("ALL", true); //true - means all message parts will be received from server

      //2nd option
      foreach (ImapX.Message m in client.Folders["INBOX"].Messages)
      {
        m.Process();
        List attachments = m.Attachments;
        string textBody = m.TextBody.TextData;
        string htmlBody = m.HtmlBody.TextData;
      }

      ImapX.Message msg = new ImapX.Message();
      msg.Subject = "hello yahoo";
      msg.From.Add(new ImapX.MailAddress(fromUserName, fromUserEmail));
      msg.To.Add(new ImapX.MailAddress(toUserName, toUserEmail));
      msg.HtmlBody.ContentType = "text/html";
      msg.HtmlBody.TextData = "it is test message";

      ImapX.Attachment atach = new ImapX.Attachment();
      atach.FileName = attachmentPath;
      msg.Attachments.Add(atach);
      if (client.Folders["INBOX"].AppendMessage(msg))
      {
        Console.WriteLine("message has been appended to INBOX");
      }

Feature list supported by library:

  • Folder management
  • Message management
  • Message saving in IMAP folder (like Drafts on Gmail)
  • SSL
  • Custom IMAP server implementations (like Google and AOL)
  • Full IMAP Search compatible

Features to be implemented during near future:

  • Offline message storage/synchronization

In ZIP archive you will find actual dll to use and IMAP Search reference document, sorry no documentation at this moment.

Hopefully it will be usefull.

Feb 24, 2010 update:

We have fixed following issues:

  1. now we correctly support message flags (“DELETED”, “SEEN”, “ANSWERED”, “DRAFT”, “RECENT”) and custom flags
  2. correctly handling spaces in passwords (need to be tested more, please contact us if you’ll find an issues there)

There are code sample which allows to set message flags:

ImapX.MessageCollection messages = client.Folders["INBOX"].SubFolder["NEWFOLDER"].Search("ALL");
//get list of current message flags
List allFlags = messages[1].Flags;
//set fllag array of flags are in ImapFlags constants
messages[1].SetFlag(ImapX.ImapFlags.SEEN);

Feb 25, 2010 update:
Today we have released version 1.0.5 of the library

Fixed issues:

  1. now correctly handling different types of subjects from IMAP

March 4, 2010 update:
Today we have released version 1.0.6 of the library with a great performance improvements (up to 4 time faster)

Fixed issues:

  1. Now it’s possible to search for messages without auto-filling the body, header and other message properties. Added new bool parameter for Search method which indicates to fill properties or no

Here is code example

//result messages  + process()
ImapX.MessageCollection messages = client.Folders["G01"].Search("ALL", true);
//result empty messages
ImapX.MessageCollection messages = client.Folders["G01"].Search("ALL", false);
//fill message header info
messages[1].ProcessHeader();
//fill message flags info
messages[1].ProcessFlags();
//fill message body info
messages[1].ProcessBody();
//fill all message info
messages[1].Process();

March 4, 2010 update:
We have updated library to 1.0.6.1 version. Fixed some minor bugs. Thanx to Dalibor.
March 25, 2010 update:
We have updated library to 1.0.6.3 version. Fixed some more minor bugs.
March 26, 2010 update:
We have updated library to 1.0.6.4 version. Added IsDebug property to ImapX.ImapClient

client.isDebug  = true; // with this option , all requests and responses are print to Console window

April 14, 2010 update:
We have updated library to 1.1 version. Fixed bugs with message processing, users faced in previous releases.
Please note: if your are facing any problems with message body or if message has no content-type, you may find all body parts in BodyParts collection:

   List<MessageContent> bodyParts = msg.BodyParts;
   //get body :
   string body = bodyParts[index].ContentStream;

Some users facing problems with different Subject/Body encodings. Please note – ImapX itself doesn’t decode subject/body automatically. For instance if you have subject encoded to BASE64 using UTF8 charset you have to do following techniques:

   //preparing subject to be sent
   string codedSubject = "=?UTF-8?B?" + Convert.ToBase64String(Encoding.UTF8.GetBytes(subject)) + "?=";
   //decoding subject from received message
   string decodedSubject = Encoding.UTF8.GetString(Convert.FromBase64String(CodedSubject.Split('?')[4]));
   //decoding body from Base64/UTF8 :
   string decodedBody = Encoding.UTF8.GetString(Convert.FromBase64String(msg.HtmlBody.TextData));

Thanks to all of users of ImapX. And thank you for you comments, your responses help us to develop better IMAP library.

April 27, 2010 update:
We have updated body processing, ImapX refused to consume some bodies produced by Outlook 2007. It’s fixed in 1.1.0.1 version

May 12, 2010 update:
Updated:

  • Message parsers updated
  • Fixed problems with special characters in folder names
  • Added body part properties: BoundaryNames and PartHeaders
    Example:

    MessageContent body = message.HtmlBody;
    body.BoundaryNames // name of boundary of this part
    body.PartHeaders // Collection headers of this part

July 7, 2010 update:
Updated:

  • Message parsers updated
  • Fixed problems with marking message as seen during processing
  • Fixed attachments processing

If you’ll face problems with a message parsing then please use method GetAsString() of class Message. It will allow you to use custom parsers to parse a message

Download

Comments
  • Leaskovski 09/28/2010 at 00:56

    Hi Guys,

    Is this compatible with the CF .Net Framework??

  • rocroc 10/01/2010 at 07:15

    I found a bug concerning the propertie “MessageIud” of class “Message” which doesn’t realy return the IUD of the mail

    if you send the command “UID fetch 1:* (FLAGS)” you’ll receive for example :
    1 FETCH (FLAGS (\Seen) UID 6)
    2 FETCH (FLAGS (\Seen) UID 12)
    3 FETCH (FLAGS (\Seen) UID 15)

    so for the first mail, the value of MessageIud will be 1 instead of 6
    for the second mail the value will be 2 instead of 12

  • Kenneth Fuglsang 10/04/2010 at 19:14

    I have been using this library but unfortunately I’m running into an issue quite often with messages that causes ImapX to throw an exception.

    In the Message.Process() method you are calling Convert.FromBase64String but this throws an “Invalid Character in Base 64 String”.

    Could you provide a .dll-file compiled in debug mode so it’s possible to step in and see what is actually wrong with these messages and possibly fix it?

    If so, please send me an email.

    Best Regards
    Kenneth
    Denmark

  • naeem 10/05/2010 at 14:52

    I have 2 attachments but i only see one attachment in Attachments but can see the attachment in BodyParts, any ideas?

  • Jonx 10/05/2010 at 18:05

    Hello, very nice library. I was looking for an event that I can suscribe too that will give me feedback in case of long running operations, like asearch for exemple…
    Also, you say I need to decode the subject/body myself… Ok, no problem. Just how can I know what the encoding is? Do I have to find this out myself each time or is there a property sowhere for that?
    Thank you, I’mm loving it anyway,
    John.

  • Matt 10/09/2010 at 00:29

    How do you search on date … I can’t get the syntax down. What format should the date be in?

    Thanks!!! Best free IMAP parser I have used!!

  • Portman 10/09/2010 at 02:45

    Connecting to GMail, the Attachments property is not being populated. I can see 4 MessageContent objects in the BodyParts property, and one of them is the 1MB jpeg attachment.

    Is this a known issue? I’ve tried it with multiple attachment types, and all have the same problem.

  • Priya 10/12/2010 at 01:09

    I am unable to connect at the first place, can you please help. It fails at the line ” result = client.Connection();” and the error message is “dont connect”

  • priya 10/14/2010 at 06:04

    How to move a message in another folder?? or label any message??

  • Arno 10/15/2010 at 12:14

    I have created an windows service that reads email messages from different folders and place them into a database. When a message contains an attachment, it wil put it on server location. It works great thanks to the nice library, but there is only one problem. When a message contains a *.doc file or *.pdf, it doesn’t appear between the attachsments in the message object.

    Does somebody has a fix for this problem?
    Thanks,

  • Casimodo 10/15/2010 at 16:16

    The following search returns all messages in the inbox, not only the ones I was searching for.
    client.Folders["INBOX"].Search(“SUBJECT \”Hello\”", true)
    Am I doing something wrong, or is your search machinery not working correctly?

  • Patrik 10/18/2010 at 17:25

    Very nice library!

    However, it marks all your mails as SEEN in GMail although I only call ProcessHeader().
    I think the IMAP implementation needs to be changed according to this official Google statement:
    http://www.google.com/support/forum/p/gmail/thread?tid=45e0936ce17bcbfd&hl=en

  • Priya 10/19/2010 at 17:49

    Does anyone ever respond here??

    When I try to create new folder and use that folder using Client.Folder["New Folder"] it gives error.

    This works fine if the folder is already created.

    Also another thing, the Move Message to folder method, does not move all the messages, it only moves half the messages??

    Can someone help??

  • Andriy Mykhaylyuk 10/19/2010 at 19:57

    Hello Priya,
    Yeah, we are responding, but really slowly, we are overloaded this days.
    What kind of IMAP server you are using?

  • cuongdx 10/25/2010 at 12:01

    HI all.
    I have some problems.If i have a attachment then attachment count =0.
    Can someone help??

  • Cesare 10/25/2010 at 13:25

    Hi,

    I have been having trouble getting messages from our mail server. It correctly identifies how many messages are there but the Imapx.MessageCollection returns strange results including blank messages, duplicates and missing messages.

    As a test we tried to get messages from GMail which worked fine, however we cannot get it to work properly against our SmarterMail mail server which uses IMAP4Rev1.

    Any Ideas?

    Cesare

  • Vsevolod 10/26/2010 at 10:33

    Hi, thanks for the great library!
    Do you still plan to make it open source? Any dates?
    Is it possible to open source codes as is, without any effort to prepare it for open source? I know you’re busy, so give as the ability to hack on the library too.
    Any plans for PUSH functionality?

  • Hugo 11/03/2010 at 20:16

    Hi, this is the very first .Net library which shows me e-mail from GMail correctly out of the box. Grats!
    How could I collect all folders (aka. labels) assigned to a particular e-mail.
    This is just the opposite approach, coming from the a message to it’s labels and not from a label to it’s messages.
    Thanks.
    Hugo

  • herry 11/08/2010 at 19:19

    Hi,
    Thank you for the library, it’s quite simple and easy to use.
    However, I think there is a bug in the search for uids.
    I think they syntax is backward.
    It should be UID SEARCH instead of SEARCH UID.
    I don’t know maybe it’s just me.
    I can’t seem to be able to search by uid.

  • Gary 11/09/2010 at 02:34

    1st, Love it. Good work, and thank you for sticking your neck’s out and publishing this!
    Are there any updates on the IMapX classes forthcoming in the near future?
    Are there any user doc(s) available? Like How-To’s, other than just this web page.
    Has there been any movement on the open sourcing of the classes?
    If you would like some assistance, in what area(s) might I be able to contribute for you?
    Thanx,
    G

  • Alistair 11/09/2010 at 16:20

    Having a problem trying to read an e-mail sent from Outlook 2010. The subject is available but the message body (text and html) is null. Any ideas how to solve this?

  • Alistair 11/10/2010 at 14:40

    I recently had some problems trying to read e-mails sent from Gmail, Outlook 2007 and Outlook 2010 (using my Gmail Imap account):
    - Gmail would populate the message.TextBody.TextData field and the message.Attachments list.
    - Outlook 2007 would populate the message.HtmlBody field but not the attachments list.
    - Outlook 2010 wouldn’t populate either of the above fields.
    I found a good open source tool that helps parse the e-mail contents (MIME types), which makes it easier and quicker to find attachments and decode the e-mail body. You can check it out at http://anmar.eu.org/projects/sharpmimetools/ . Hope this helps.
    AL

  • Qnavry 11/15/2010 at 20:17

    I am having the same issue with the attachments as others are. I see the attachment in the BodyParts but the attachment count is 0. Any Ideas?

  • Gary 11/16/2010 at 00:54

    Getting more desperate :-(
    trying to use ImapX.Message.SaveAsEmlToFile(DirName, FileName) which is NOT throwing an exception in a try/catch… but is not saving a file.
    Ouch!
    thanx,
    G

  • Gary 11/16/2010 at 02:40

    OK, more info.
    ImapX.Message.SaveAsEmlToFile() works on a WinForm app built as .Net 3.5.
    But does not work in a class library built as .Net 2.0 called by a web app.
    The permissions on the path being written are for “Everyone” and include “Create files / write data”.
    Interestingly, from the class library, if i copy a file into the path using the same name that SaveAsEmlToFile() will use, when i run the web app, it deletes the file..
    weird!

  • David 11/17/2010 at 06:42

    Hi, I was wondering a couple of things:
    1) is there any way to flag the message as read when doing folder.Search? I actually need to flag messages as read as soon as I download them and I’m downloading about 1000 mails per batch, so it takes quite some time.

    2) In your experience with the IMAP protocol, do you think using an Asyncronous pattern would save some time in this mail-checking process?

  • David 11/17/2010 at 16:31

    Question: Do you guys mind if I just run reflector on your code, implement point number one rebuild and send the binaries (or the source) back to you so you can publish it here?

  • alhambra eidos 11/25/2010 at 13:22

    hi, source code will be in codeplex ?? thx

  • David 11/28/2010 at 19:12

    Hi, I reflectored your code and implemented the above changes. I also noticed you are reading from the stream untill newlines. I have worked a bit with streams and have found that (for me) the fail-safe way to read from a specific stream is to read untill a token is found. Since the RFC3501 specifies that the response of the server always ends with *[YourCommandIdentifier] (IE *IMAP000 OK), I would suggest in the sendAndRecieve method you dont look for newlines, but read the whole thing utill the *IMAPXXX token is found. This way you also enable the sendAndRecieve method to work safely under an Asyncronous architecture if at any point in time you wish to implement that.

  • David Honess 12/06/2010 at 11:18

    Dear all, I am using your ImapX DLL to download some file attachments from google. After downloading the message I set the \Seen flag and then move it to the Bin folder. This works well, however I have found a problem when I use this code inside a for loop. My code gets a list of all unseen emails and then loops through them using a foreach on the message object. I have found that only the first message gets moved to the Bin, subsequent messages just appear to be lost. Am I doing something wrong?

    Here is my code;
    foreach (ImapX.Message msg in unseenMessages)
    {
    if (msg.Headers["Subject"].Contains(_subjectFilter))
    {
    MessageContent theFilePart = msg.BodyParts.Find(part => part.ContentType.Contains(_fileType));

    if (theFilePart != null)
    {
    string filename = StringHelper.ExtractQuotes(theFilePart.ContentType);

    byte[] dataBytes = CryptographyHelper.DecodeBase64String(theFilePart.ContentStream);
    System.IO.File.WriteAllBytes(string.Concat(_outputPath, filename), dataBytes);
    emailDownloaded = true;
    msg.SetFlag(“\\Seen”);
    }

    if (emailDownloaded)
    {
    if (!string.IsNullOrEmpty(_imapMoveToFolder))
    {
    Folder moveTo = theClient.Folders.Find(item => item.Name.Equals(_imapMoveToFolder, StringComparison.InvariantCultureIgnoreCase));

    if (moveTo != null)
    {
    inbox.MoveMessageToFolder(msg, moveTo);
    }
    }
    }
    }
    }

  • Waldemar 12/07/2010 at 10:42

    Hi guys, thanks for the lib.
    I’ve only two questions:
    1. I’ve got a plain-text e-mail where the body is formated in ISO-8859-15. Is it possible to access the original bytes, because in TextBody.TextData every charectar above 0×80 is replaced by ‘?’ ?
    2. My second question is, whether it is possible to mark an e-mail as unread on the imap-server?
    BR
    Waldemar

  • Chad Ostler 12/08/2010 at 19:26

    Hi and thank you for imapx it seems to work very well. I however am having problems with processheaders on a message where it marks the message as read. Is this intended? How can I process headers without it marking email as read?

    Thanks,
    Chad

  • Michael Kubarycz 12/14/2010 at 19:16

    File Attachment Issue:
    This seems to be a bug when parsing HTML email messages. The first attachment is not parsed correctly and doesn’t get added to the Message.Attachments collection. A plain-text email does not have the same issues. Very nice tool otherwise. Have the authors thought about making the source available?

  • Michael Kubarycz 12/14/2010 at 19:55

    This works for me. Would be nice if there was a Message.ToStream() or Message.ToBytes() method. You currently only have the option to save the message (Message.SaveAsEmlToFile()) and then open up a filestream.

    Alistair
    I recently had some problems trying to read e-mails sent from Gmail, Outlook 2007 and Outlook 2010 (using my Gmail Imap account):
    - Gmail would populate the message.TextBody.TextData field and the message.Attachments list.
    - Outlook 2007 would populate the message.HtmlBody field but not the attachments list.
    - Outlook 2010 wouldn’t populate either of the above fields.
    I found a good open source tool that helps parse the e-mail contents (MIME types), which makes it easier and quicker to find attachments and decode the e-mail body. You can check it out at http://anmar.eu.org/projects/sharpmimetools/ . Hope this helps.
    AL

  • James 12/21/2010 at 23:50

    Hi i would like to use this library with vb 2010 is there any documentation as to how to implement this into a vb.net project? Thanks anyways guys im kind of a noob anyway

  • SRIJAN ROY 12/24/2010 at 12:02

    I want to disable Automatic SEEN FLAG set for the New Mail Until I set it. How to Achieve that?

  • Nikos Bilalis 12/25/2010 at 15:04

    For decoding Subject/Body

    private static string Decode(string input)
    {
    var ret = new StringBuilder();
    var re = new Regex(@”\=\?(?[^?]+)\?B\?(?[^?]+)\?\=”);
    var matches = re.Matches(input);

    if (matches.Count == 0) return input;

    foreach (Match match in matches)
    {
    var enc = Encoding.GetEncoding(match.Groups["encoding"].ToString());
    ret.Append(enc.GetString(Convert.FromBase64String(match.Groups["text"].ToString())));
    }

    return ret.ToString();
    }

  • Nikos Bilalis 12/25/2010 at 15:07

    It messed up my code a little bit -> http://pastebin.com/TFGpkmuu

  • Cristian 12/31/2010 at 19:37

    Hi all… great library !!
    I was investigating about IMAP in .net.
    I have a little problem… I want to know the labels about an email but I didn’t find any propertie in ImapX.Message.
    Any idea about that?
    Thanks!

  • kiran 12/31/2010 at 20:33

    Hi, 1st of all thanx a ton 4 d library.
    I want to read the unread mails from INBOX. How to do that ? ie, whenever a new mail comes the application must know that. For that, we need to get the Unread mails. How to do with imapx? Any help is much appreciated.

    Thanks in advance

  • SRIJAN ROY 01/02/2011 at 20:27

    How to Process the Mail Body WITHOUT Attachment. Cause While Processing the Body with Attachment takes Long time. So, If attachment and Body are Processed Separately then It will be Better.

  • Revan1985 01/11/2011 at 14:25

    Hi.
    I’m using your library in a personal project.
    It’s very usefull.
    I’ve a little problem with attachments…
    If the email had a txt as attchment, the library crash because it’s not handled the case when an attachment isn’t decoded in base64.
    I’ve another problem.
    The library had a logic strange. sometimes i can found an allegate like pdf, other times not. why?
    The library is great and usefull, only this 2 bug are strange.
    You have idea to release the source code or will be closed source but free to use?
    Thanks for all guys ^^

  • Me 01/14/2011 at 15:37

    Hello,

    Is it possible to remove the SEEN-Flag of a Mail?

  • Jeff 01/18/2011 at 00:08

    Works great except I’m having content type encoding issues. No-matter how I access the message body (HtmlBody/TextBody/BodyParts[i]), using GetAsString or .TextData, I always end up with characters like “=A0″ in the resulting string. Is there a way to access the raw bytes of the MIME part retrieved, or a way to use a 3rd party tool to access the message content directly? Or is this a known bug?

  • Serg 01/19/2011 at 17:26

    Hello.
    Is it possible to get imap quota with imapX library

  • Dan 01/28/2011 at 02:29

    I’m trying to delete messages. I set the \Deleted flag but I can’t seem to find how to issue the expunge command. I did try imap._client.sendcommand(“. expunge”) and imap._client.sendcommand(“expunge”) – but no luck. I’m talking with an exchange 2003 server. Thanks for the help!

  • Dan 01/28/2011 at 02:46

    Dan
    I’m trying to delete messages. I set the \Deleted flag but I can’t seem to find how to issue the expunge command. I did try imap._client.sendcommand(“. expunge”) and imap._client.sendcommand(“expunge”) – but no luck. I’m talking with an exchange 2003 server. Thanks for the help!
    Comment awaiting moderation.

    I just figured it out! imap._client.SendData(“. expunge” & ControlChars.CrLf)

    I was trying to use the sendcommand function but I needed to use the senddata function along with a new line character. Thanks for a very nice library!

  • Oscar 01/31/2011 at 23:29

    Hey guys – nice library!

    I’m trying to use it for a small personal project inserting mail messages into my Gmail account.

    I’ve run into a couple of problems when creating new messages (e.g. the date header is not formatted correctly and can’t be overridden by explicitly adding the header to the header collection; can’t create a non-base64-encoded HTML body; etc).

    Many people have asked if you’re planning on releasing the source to this library. I’d like to know, too, and think it would be a great resource for the .Net community. There don’t seem to be any well-maintained open source IMAP projects out there currently.

  • chad 02/01/2011 at 05:41

    is there support for idle or push?

  • Colin 02/17/2011 at 18:18

    Please could I get some help – I am trying to connect using the supplied (standard) Google IMAP server but all I am getting is “dont connect”. Thank you for a great product!

  • Post a comment
    You must be logged in to comment. Log in
1 2 3 4 5
Trackbacks