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.
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);
else
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
{
get
{
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("imap.gmail.com", 993, true, @"mailaddress@gmail.com", "password");
foreach (Message email in rep.GetUnreadMails("Inbox"))
{
Response.Write(string.Format("<p>{0}: {1}</p><p>{2}</p>", email.From, email.Subject, email.BodyHtml.Text));
if (email.Attachments.Count > 0)
{
foreach (MimePart attachment in email.Attachments)
{
Response.Write(string.Format("<p>Attachment: {0} {1}</p>", 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.

How can I insert the dll to wpf?
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.
Thank you very much. Your example works perfectly!!
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 173.194.70.108:993.
Pls help me…!
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: http://lmgtfy.com/?q=A+connection+attempt+failed+because+the+connected+party+did+not+properly+respond+after+a+period+of+time%2C+or+established+connection+failed+because+connected+host+has+failed+to+respond+
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
hoang – try mail.BodyText.TextStripped instead of email.BodyText
a problem occurred when retrieving mail.eg: 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?
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
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 (http://www.fiddler2.com), NetTool (http://nettool.sourceforge.net/) and especially Wireshark (http://www.wireshark.org/) 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:
- http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_24942090.html
- http://social.msdn.microsoft.com/Forums/da-DK/ncl/thread/29cabe89-db35-48ae-bc54-91b583eeed55
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
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.
Hi,
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.
Thanks
FYI – You can speed up your login by using Imap4Client.LoginFast() and then lazy load whatever you need.
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
how to send mails using this IMAP server url?
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 173.194.70.108:993.
same problem persist for me also while connection to gmail (imap.gmail.com)
why this application dose not work in .net windows form application. it only works on web application
hi sir,
your sample worked perfectly for me.. thanks a lot.. can u pls let me know how to get mails from send folder..
Good stuff! Thanks for sharing.
Thank you for your effort.
Would you please provide us with any book that contains tutorials about mailsystem.net
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.