Receive unseen emails using IMAP

This article describes how to receive unseen email messages using Mail.dll .net email library and IMAP protocol.

As a prerequisite you need to add reference to Mail.dll to your project. Please check MSDN how to add reference article for details.

When your reference is added you need to import correct namespaces:

// C#

using Limilabs.Mail;
using Limilabs.Client.IMAP;
' VB

Imports Limilabs.Mail
Imports Limilabs.Client.IMAP

First thing you need to do is to connect to your IMAP server. Use Connect(string host) method to connect to the server. Typically IMAP server is working on port 143. You can use Connect(string host, int port) overload when you need to specify different port, or ConnectSSL methods to use IMAP over SSL.

// C#

using (Imap imap = new Imap ())
{
    imap.Connect("imap.example.com");  // or ConnectSSL for SSL
    imap.UseBestLogin("user", "password");

' VB

Using imap As New Imap ()
    imap.Connect("imap.example.com")   ' or ConnectSSL for SSL
    imap.UseBestLogin("user", "password")

Next step is to select folder, download unique ids (uids) of unseen messages, and iterate through them. In this exmaple we select inbox, but you can use Select method to select different folder.

// C#

imap.SelectInbox();
List<long> uids = imap.Search(Flag.Unseen);
foreach (long uid in uids)
' VB

imap.SelectInbox()
Dim uids As List(Of Long) = imap.Search(Flag.Unseen)
For Each uid As Long In uids

Finally we’ll use GetMessageByUID method to download the message from the server and MailBuilder class to parse it and extract attachments:

// C#

var eml = imap.GetMessageByUID(uid)
IMail email = new MailBuilder().CreateFromEml(eml);

Console.WriteLine(email.Subject);
Console.WriteLine(email.Text);
' VB

Dim eml = imap.GetMessageByUID(uid)
Dim email As IMail = builder.CreateFromEml(eml)

Console.WriteLine(email.Subject)
Console.WriteLine(email.Text)

At that point you can also access attachments.

Here are the full samples in C# and VB.NET:

// C#

using Limilabs.Mail;
using Limilabs.Client.IMAP;

class Program
{
    static void Main(string[] args)
    {
        using(Imap imap = new Imap())
        {
            imap.Connect("imap.example.com");   // or ConnectSSL for SSL
            imap.UseBestLogin("user", "password");

            imap.SelectInbox();
            List<long> uids = imap.Search(Flag.Unseen);

            foreach (long uid in uids)
            {
                var eml = imap.GetMessageByUID(uid);
                IMail email = new MailBuilder()
                    .CreateFromEml(eml);

                Console.WriteLine(email.Subject);
                Console.WriteLine(email.Text);
            }
            imap.Close();
        }
    }
};
' VB.NET

Imports Limilabs.Mail
Imports Limilabs.Client.IMAP

Public Module Module1
    Public Sub Main(ByVal args As String())
        Using imap As New Imap()
            imap.Connect("imap.example.com")   ' or ConnectSSL for SSL
            imap.UseBestLogin("user", "password")

            imap.SelectInbox()
            Dim uids As List(Of Long) = imap.Search(Flag.Unseen)

            For Each uid As Long In uids
                Dim eml = imap.GetMessageByUID(uid)
                Dim email As IMail = New MailBuilder() _
                    .CreateFromEml(eml)

                Console.WriteLine(email.Subject)
                Console.WriteLine(email.Text)
            Next
            imap.Close()
        End Using
    End Sub
End Module

Tags:    

Questions?

Consider using our Q&A forum for asking questions.

16 Responses to “Receive unseen emails using IMAP”

  1. Receive iCalendar meeting request | Blog | Limilabs Says:

    […] You can use both IMAP or POP3 protocol to download email from the server. […]

  2. Receive vCard business card | Blog | Limilabs Says:

    […] You can use both IMAP or POP3 protocol to download email from the server. […]

  3. Chris Blaisdell Says:

    How do I mark them as seen after I receive them?

  4. Limilabs support Says:

    @Chris,

    If you are using GetMessageByUID to download email message, most IMAP servers will automatically mark such message as seen.

    You can check this article for details: mark emails as seen.

  5. Ajay Says:

    Hi,

    When I get all emails with Uid larger than last sync, How can I find out if particular mail is seen or unseen (read or unread)? I do not want to get the mails using Flag.Unseen as I need to sync all the mails to the client read or unread (user might have seen the mail on other client, in that case I need to show that mail as read/seen on my client)

    Thanks for your help.

  6. Limilabs support Says:

    @Ajay,

    There are several way to achieve it:

    1.
    You can make a second search for unseen emails:

    List<long> unseenUIds = imap.Search(Flag.Unseen);
    

    Searches are efficient, as they only download uids. Especially unseen search, as most users only have several unseen messages.

    2.
    You can use GetMessageInfoByUID method that takes uid list as a parameter:
    http://www.limilabs.com/blog/get-email-information-from-imap-fast
    Resulting list contains many email information (subject, attachments count and names, date, from, to headers) and flags for each email. Unseen messages should contain Flag.Unseen flag in MessageInfo.Flags.Flags collection.

  7. Ajay Says:

    For option 1, Can I combine the search criteria, like flag.Unseen and Uid greater than last sync?

    Thanks.

  8. Limilabs support Says:

    @Ajay,

    Of course, use Expression.And:

    var query = Expression.And(
            Expression.UID(Range.From(largestUID + 1)),
            Expression.HasFlag(Flag.Unseen)
        );
    List<long> uids = imap.Search(query);
    

    More info on searching IMAP here.

    Still searching for unseen messages should be very fast, even without the UID range part.

  9. Puneet Says:

    I tried to use this but I am getting exception i.e. Unable to read data from the transport connection: An existing connection was forcibly closed by the host..

    Please provide your inputs

  10. Limilabs support Says:

    @Puneet,

    Please disable your firewall and antivirus software. Are you sure you’ve provided all connection settings correctly? At which line did it happen? Consider reading this article if you have problems connecting.

  11. Puneet Says:

    I have a requirement to read incoming email subject, body and attachment. There may multiple email addresses which I have to read using single application. Till now what I discovered from your site this can be acheived using different configurations. Requesting to confirm whether my understanding is correct?

  12. Limilabs support Says:

    @Puneet,

    I’m not sure what “configurations” are you talking about, but if you have multiple accounts to check, you’ll need to connect and login to IMAP server for each of them separately.

  13. Puneet Says:

    As a part of requirement I have multiple email addresses and I have to write any application to read the emails from these email addresses.
    I should login with 1st email address then read and loggoff. Re-login with second email address and repeat same steps. Am I correct?

  14. Limilabs support Says:

    @Puneet,

    You should connect, login, read emails and disconnect (IMAP does not have log off command). Repeat those steps if needed.

  15. vescan Says:

    Is there anyway to retrieve all emails from a certain IMAP folder using one select and not one by one using GetMessageByUID. i dont know why, but for me getting emails one by one is very slow (2 emails per second)
    TIA

  16. Limilabs support Says:

    @vescan,

    You can try getting only most important email data without downloading actual emails.