Reading mails using IMAP and MailSystem.NET

In this article I will describe how you can use C# and MailSystem.NET to read mails from any IMAP source, including GMail.

MailSystem.NET is a Open Source, GNU Library General Public Licensed library for managing emails using SMTP, POP3, IMAP and many more protocols.

Download MailSystem.NET here.

I needed a component that will read mails from an IMAP source and import them into Sitecore. So I built this simple repository to get me all mails from a certain mailbox. Here is how I did it.

First you need to copy ActiveUp.Net.Common.dll and ActiveUp.Net.Imap4.dll from the MailSystem.NET package to your /bin/ folder.

Reading from MailSystem.NET is pretty straight forward:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ActiveUp.Net.Mail;

namespace PT.MailIntegration.IMAP
  public class MailRepository
    private Imap4Client _client = null;

    public MailRepository(string mailServer, int port, bool ssl, string login, string password)
      if (ssl)
        Client.ConnectSsl(mailServer, port);
        Client.Connect(mailServer, port);
      Client.Login(login, password);

    public IEnumerable<Message> GetAllMails(string mailBox)
      return GetMails(mailBox, "ALL").Cast<Message>();

    public IEnumerable<Message> GetUnreadMails(string mailBox)
      return GetMails(mailBox, "UNSEEN").Cast<Message>();

    protected Imap4Client Client
        if (_client == null)
          _client = new Imap4Client();
        return _client;

    private MessageCollection GetMails(string mailBox, string searchPhrase)
      Mailbox mails = Client.SelectMailbox(mailBox);
      MessageCollection messages = mails.SearchParse(searchPhrase);
      return messages;

This repository can now be used to read all mails or all unread mails from a mailbox. The constructor takes the mail server name, port and SSL information, as well as the email address and password of the account to read from. GetAllMails() read all mails from the specified mailbox, while GetUnreadMails() reads all unread mails. Both functions returns a list of Message objects. A Message is the complete email in one object.

To read from a GMail mailbox you need to connect using SSL on port 993:

using ActiveUp.Net.Mail;
using PT.MailIntegration.IMAP;

protected void TestMail()
  MailRepository rep = new MailRepository("", 993, true, @"", "password");
  foreach (Message email in rep.GetUnreadMails("Inbox"))
    Response.Write(string.Format("{0}: {1}


", email.From, email.Subject, email.BodyHtml.Text));
    if (email.Attachments.Count > 0)
      foreach (MimePart attachment in email.Attachments)
        Response.Write(string.Format("Attachment: {0} {1}

", attachment.ContentName, attachment.ContentType.MimeType));

Other IMAP mail servers might not need SSL, or requires another port number.

When calling GetUnreadMails(), mails will be marked as read afterwards.

Please note that reading using IMAP (at lest from GMail accounts) is very slow. Don’t be surprised if it takes up to a minute to get 30 mails from a mailbox.


About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .net, c# and tagged , , , , , . Bookmark the permalink.

71 Responses to Reading mails using IMAP and MailSystem.NET

  1. moyt says:

    How can I insert the dll to wpf?

  2. Paul says:

    Is there any way of using OAuth 2.0 with the MailSystem.NET in the code sample the username, password combination. For some applications however you are unlikely to have that combination.

  3. Ognjen says:

    Thank you very much. Your example works perfectly!!

  4. nagendra says:

    I am getting the following error.

    A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
    Pls help me…!

  5. briancaos says:

    The message implies that there is no connection between your server and the IMAP server you are trying to connect to.
    For further information try this link:

  6. hoang nguyen says:

    I need to get the contents of the mail.if used “email.BodyHtml.Text” then it automatically insert HTML code.I try “email.BodyText” but is not, please help me

  7. Paul Chapman says:

    hoang – try mail.BodyText.TextStripped instead of email.BodyText

  8. hoang nguyen says:

    a problem occurred when retrieving in gmail, mail sent to the Inbox, 2 mail has the same title, it will be classified in the same group.While it only took a second mail, mail for no gain.How do I fix this problem?

  9. Leena says:

    hi , your article is very good
    when i use your code, while connecting to our imap server, its give me following message:
    Unable to read data from the transport connection: An established connection was aborted by the software in your host machine.

    any idea, what can be problem

  10. briancaos says:

    This exception is thrown when the mail server you are requesting closes the connection. You need to ensure that you are requesting data from the correct port, and use SSL if needed.
    You should also ansure that your firewall and antivirus allows you to send AND receive data from the port you are requesting. McAfee antivirus for example is known for blocking mail send requests.

    Detecting network related issues is very difficult but tools like Fiddler (, NetTool ( and especially Wireshark ( is great tools for seeing what’s going on between your machine and the target host.

    The following articles gives you a more technical description of the issue:

  11. nitin says:

    hey here UNSEEN is not working as it gives a error saying that
    “object reference not set ot an instance of object ” pointing out the
    line -“messagecollection messages=mails.SearchParse(searchphrase);
    can u please help me out it’s important part of my academic project please reply me soon thnks

  12. briancaos says:

    The “UNSEEN” is a mail server search phrase describing to the mail server that it must return all unread mails from the inbox.
    Not all mailservers uses this phrase. Please refer to the manual of your mailserver what phrase to use when looking for unread mails.

  13. Saif says:

    Nice article with good information. I have following query, if you can help?
    – Can we identify from Headers if email have attachments?
    I want to display attachment icon with email information same hotmail, gmail inbox.


  14. FYI – You can speed up your login by using Imap4Client.LoginFast() and then lazy load whatever you need.

  15. Eduardo says:

    I am getting the following error.

    “The remote certificate is invalid according to the validation procedure”,

    Where do i have to specify the certificate or is there a method which allows me to skip the validation. Can you please help me out

    Thanks in advance

  16. Krishna Varma says:

    how to send mails using this IMAP server url?

  17. Raveesh G S says:

    A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

    same problem persist for me also while connection to gmail (

  18. WGHS says:

    why this application dose not work in .net windows form application. it only works on web application

  19. vinodh says:

    hi sir,
    your sample worked perfectly for me.. thanks a lot.. can u pls let me know how to get mails from send folder..

  20. Bob Taylor says:

    Good stuff! Thanks for sharing.

  21. Samer says:

    Thank you for your effort.
    Would you please provide us with any book that contains tutorials about

  22. Thanx on library.
    Is there a chance to count unread messages without setting flag on IMAP server readed.
    When I do mails.SearchParse(“UNSEEN”);
    All messages get status readed.

  23. Martin H says:

    I`ve got a question, the “UNSEEN” messages are not marked as “read” after i executet the programm. Do you know why this could happen ?

  24. Pooja says:


    I have a requirement to read link from the email body and go to the link. Is there any way in the library to get the link in email body or we need to manually scan the email body to get the link?


  25. EzLo says:

    Admin Hod:

    To count unread messages just use mailbox.messageCount and substract the ordinal position of the first unseen message in the mailbox using the property of the mailbox called “firstunseen”.


    There is no way with to determine a link within the body of a mail. You will have to parse it yourself unfortunately.


    To open mails from the Sent mailbox, just need to select that mailbox instead of Inbox. However, different mail servers (gmail, yahoo, etc) name the “Sent” mailbox differently (for example its [Gmail]/Sent with gmail with an english account or [Gmail]/Enviados with a spanish account). To figure out the exact name, you can issue a “List” command, or you can debug and check the “allMailboxes” property of an already connected Imap4Client (which was connected by login method and not by fastLogin).

    Krishna Varma:

    IMAP is only for retrieval of mails, to send one you need to use Simple Message Transfer Protocol (SMTP) which has different host, port and commands (still supported with though).

    Martin H:

    Unseen mails are mails that do not posess the “seen” flag. There isn’t a “not seen” flag. The way to adquire the Message object in determines whether this flag is automatically eliminated or not. Use mailbox.Fetch.messageObject(…) to get the Message object and setting the “seen” flag, or use mailbox.Fetch.messageObjectPeek(…) to get the Message object without chaging the “seen” flag (so mails not seen will remain the same.
    If you use mailbox.searchPhrase(…), the server will always add the “seen” flag (there is a workaround this but its like bypassing MailSystem library, by issuing a Command with BODY.PEEK parameter).

    Hope this helps!

  26. hasanein says:

    give me error,the method is must return type( MailRepository

  27. Manve says:

    How to Monitor mail server for incoming mails? Threading? or is there any inbuilt method to do it?

  28. Marc says:

    Hi, I tried this library with Gmail. Got a successful connection but it took ages to do the login even though it eventually succeeded.

  29. Suresh says:

    It works perfectly…. I would like to download the attachment…. how I should do it could you please help me….

  30. Timeternity says:

    Client.Login(login, password) => Client.LoginFast(login, password);
    It can resolve the very slow problem.

  31. Ameli says:

    How to import folders from one imap email client for C #?

  32. What the says:

    Where the [][] is your response (Response.Write(…)). What the [][] is Response? A tree? A potato?

  33. briancaos says:

    Yes it’s a tree. No, its a test function on an .aspx page from a web project. The Response.Write() is part of the HttpContext.Current. namespace.

  34. Thank you for this, i made a few additions. public class MailRepository
    private Imap4Client _client;

    public MailRepository(string mailServer, int port, bool ssl, string login, string password)
    if (ssl)
    Client.ConnectSsl(mailServer, port);
    Client.Connect(mailServer, port);
    Client.Login(login, password);

    public IEnumerable GetAllMails(string mailBox)
    return GetMails(mailBox, “ALL”).Cast();

    public IEnumerable GetAllTo(string mailBox, string emailFilter)
    var test = GetMails(mailBox, string.Format(“TO ‘{0}'”, emailFilter)).Cast();
    return test;

    public IEnumerable GetAllToFromDate(string mailBox, string emailFilter, DateTime date)
    var dateFormatted = date.ToString(“dd-MMM-yyyy”);
    var test = GetMails(mailBox, string.Format(“TO ‘{0}’ NOT BEFORE {1}”, emailFilter, dateFormatted)).Cast();
    return test;

    public IEnumerable GetMailsFromDate(string mailBox, DateTime date)
    var dateFormatted = date.ToString(“dd-MMM-yyyy”);
    return GetMails(mailBox, string.Format(“NOT BEFORE {0}”, dateFormatted)).Cast();

    public IEnumerable GetUnreadMails(string mailBox)
    return GetMails(mailBox, “UNSEEN”).Cast();

    public IEnumerable GetUnreadMailsFromDate(string mailBox, DateTime date)
    var dateFormatted = date.ToString(“dd-MMM-yyyy”);
    return GetMails(mailBox, string.Format(“UNSEEN NOT BEFORE {0}”, dateFormatted)).Cast();

    protected Imap4Client Client
    get { return _client ?? (_client = new Imap4Client()); }

    private MessageCollection GetMails(string mailBox, string searchPhrase)
    Mailbox mails = Client.SelectMailbox(mailBox);
    MessageCollection messages = mails.SearchParse(searchPhrase);
    return messages;

  35. Diego says:

    Thaks, it works very fine. Compliments….

  36. Deepak says:

    “The handshake failed due to an unexpected packet format”. Error is coming while executing the application.

  37. vishwaram says:

    Thanks a lot.. It works great and downloads normal files(non password protected) which is attached to the mail.
    but when i try to download a zip file(which contains a password protected pdf), i am unable to open the zip file. It says its corrupted.
    I am able to download from gmail directly. Also the zip asks for password only while extracting the content. Not while downloading.

    any idea how to download password protected files via Activeup.Net?

  38. Mithlesh says:

    I am looking for how to use Search Phrases while filtering for email. I do not want to see all Unread or all read. But I need to see the emails from a particular sender & in a particular date interval.

    Pls help me how can i do that. Is there any documentation available how I can use searching for emails ?

  39. Filipe Lourenço says:

    Any 3.5 framework version?

  40. Moh Ahmed says:

    Thanks a lot, it’s worked.

    but I need to display inline attachments like images.
    How is that?

  41. sasi says:

    The operation is not allowed on non-connected sockets.

  42. sasi says:

    I got this Error…..

    The operation is not allowed on non-connected sockets.

  43. junaid says:

    i want to develop an app on getting unread mails and send these emails to mobile number as text message,i m begginer plz help me

  44. Dhruv says:

    What is the maximum number of messages that can be retrieved at a time from the mail server ? Can we retrieve 500 messages at a time? And can we retrieve messages in groups (say a group of 50 messages at a time ? Please help

  45. Rehan Nadeem says:

    Could not load file or assembly ‘ActiveUp.Net.Imap4’ or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded

    Getting this error

  46. quiconait says:


    Any 3.5 framework version, please?

    Thank’s in advance

  47. Amol says:

    How can i use pop3 and exchange server??

  48. mayur says:

    how to save attachment to sql server database

  49. mayur says:

    foreach (MimePart attachment in emails.Attachments)
    attachment .????????

  50. mayur says:

    when login through “Client.Login(login, password); ” using imap yahoo mail I got System.StackOverflow Exception

  51. Sewerrat says:

    I used gmail imap, used code above. The login is successful, but I got error “Index and length must refer to a location within the string. Parameter name: length” at line “MessageCollection messages = mails.SearchParse(searchPhrase);”. Anyone got this problem?

  52. Jonathan says:

    Has anyone seen a case where the email.Attachments AttachmentCollection doesn’t show anything within the collection, yet the email does in fact have an attachment? I have a program that is running successfully on a number of emails where the program is able to determine that there are attachments with the email. However, I am running into a case where the email has a .CSV file attachment, yet the Attachments collection is empty. The program has worked well with many other CSV attachments, so I am not at all clear as to why it would fail on this email. Hoping someone can help as this has just become a critical issue for me on a big project.

  53. Sewerrat y have the same problem did you solved it?? Thanks!!!

  54. Kulvinder Singh says:

    Too many simultaneous connections?

  55. lmgc92 says:

    hey thanks for the example: i have a question.
    how can i get emails from a public folder?
    i use this
    var inbox = imap.SelectMailbox(“MyPublicFolder”);

    but don´t works!
    plz help!

  56. I get an error
    No connection could be made because the target machine actively refused it
    on Client.ConnectSsl(mailServer, port);
    Trying to connect, 993

    Is it because of the Proxy I am behind?

  57. No connection could be made because the target machine actively refused it
    Trying to connect, 993

    Because of Proxy??

  58. Pu Wii says:

    I am having the same problem as @Jonathan, where the email.Attachments.count=0, yet the email does have an attachment. It worked initially, but suddenly, whatever I try, the Attachments collection is empty.

    @Jonathan, did you find the cause of this problem? Or even a workaround? I thought this part of my project was over and done with. Suddenly, at implementation stage, I am stuck.

    Any help/guidance would be appreciated.

    Thanks in advance

  59. Duy Nguyen says:

    How can i get the list draft email ??

  60. Venkat Kondaveeti says:

    Thank you very much

  61. briancaos says:

    All of the mail boxes are found using the searchPhrase. And since each mail server have their own set of names for folders, you will have to either find the documentation or to guess your way out of it.
    Have you tried with “drafts” or “draft”?

    GetMails(mailBox, “DRAFTS”).Cast();

    GetMails(mailBox, “DRAFT”).Cast();

  62. Zonke Msibi says:

    Hi i have tried the same code it worked but some hours the GetUnreadEmails is no longer working. The error message is as follows ” Input string was not in a correct format.” on GetMails method. Can anyone help me with this.
    public IEnumerable GetUnreadMails(string mailBox)
    return GetMails(mailBox, “UNSEEN”).Cast();

  63. saeideh says:

    Thanks for the post! I have a question! How can I Fetch the single message using its Id?

  64. Hi, I ‘m having trouble reading the mail from the IMAPClient , when do the Mailbox.Fetch.MessageObject ( x ) the body of the mesage both BodyHTML as BodyText me is empty , I could you indicate why ?

    Thank you very much.

  65. venkat says:

    I have the problem when i try to retrive mails from Godaddy workspace mail
    private MessageCollection GetMails(string mailBox, string searchPhrase)
    Mailbox mails = Client.SelectMailbox(mailBox);
    MessageCollection messages = mails.SearchParse(searchPhrase);
    return messages;

    For me SearchParse method givng error but it is connecting to godaddy

    How can i solve this problem

    Venkat Kondaveeti

  66. LE ANH XUAN says:

    How to download File Attachments to disc

  67. Ranjan says:

    How i can delete the read mail from the server..Please help

  68. Jeff says:

    To save the attachments to disk:

    Imports ActiveUp.Net.Mail
    Imports PT.MailIntegration.IMAP
    Dim rep As New MailRepository(“YourEmailDomain”,143, False,”YourEmailAddress”,”Password”)
    For Each email As Message In rep.GetAllMails(“Inbox”)
    If email.Attachments.Count > 0 Then
    For Each attachment As MimePart In email.Attachments
    File.WriteAllBytes(“D:\” & attachment.Filename, attachment.BinaryContent)
    End If

    I’m also looking for the same solution as Ranjan – Delete message after read

  69. Jeff says:

    Hopefully you don’t mind I share OpenPop solution here.
    In your project, go to Website > Manage NuGet Pakages and then install OpenPop.Net

    Imports OpenPop
    Imports OpenPop.Pop3
    Imports OpenPop.Mime.Header
    Imports OpenPop.Mime

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    ‘ Connect to the server
    client.Connect(“YourEmailDomain”, 110, False)
    client.Authenticate(“EmailAddress”, “Password”, Nothing)
    Dim messageCount As Integer = client.GetMessageCount()
    Dim allMessages As New List(Of Message)(messageCount)

    For i As Integer = messageCount To 1 Step -1
    Dim headers As MessageHeader = client.GetMessageHeaders(i)
    Dim from As RfcMailAddress = headers.From
    Dim subject As String = headers.Subject
    Dim mailMsg As Message = client.GetMessage(i)

    Dim msgHtml As MessagePart = mailMsg.FindFirstHtmlVersion()

    ‘ Display the message or you can save it to database
    Label1.Text = Label1.Text & “From: ” & from.ToString & “Subject: ” & subject & “” & System.Text.Encoding.UTF8.GetString(msgHtml.Body) & “”

    ‘ Save the full message to disk
    Dim msgFile As New FileInfo(“D:\Test.eml”)

    ‘ Save attachment
    For Each attachment As MessagePart In mailMsg.FindAllAttachments()
    ‘ if you want to check the attachment file name
    ‘If attachment.FileName.Equals(“useful.pdf”) Then …
    File.WriteAllBytes(“D:\” & attachment.FileName, attachment.Body)
    ‘ Delete Message
    End Sub

  70. Shashida nand says:

    I am having quite puzzling issue. I am able to fetch from one gmail id (corporate plan) but not other.
    When I run my .exe for other gmail id, the process runs forever and i have to forcefully close it. One time I got error as “No such host is known
    at PcrmInMail.MailRepository..ctor(String mailServer, Int32 port, Boolean ssl, String login, String password)”

    Request suggest what should i do.

    I am using configuration as below –, 993, true

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your 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