---
title: "Watch for new mail with IMAP IDLE in C#"
url: https://recursiveai.org/onemail/cookbook/watch-imap-mailbox-for-new-messages/
description: "Get new-email notifications with IMAP IDLE in C#. Watch the inbox count with OneMail and stop IDLE cleanly before sending another command."
version: "1.0.1"
---

# Watch for new mail with IMAP IDLE in C#

**OneMail** is a free, open-source email library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneMail.Client) · [GitHub](https://github.com/recursive-ai-oss/onemail-csharp) · [Docs](https://recursiveai.org/onemail/docs/) · [Download example (.zip)](https://recursiveai.org/onemail/cookbook/watch-imap-mailbox-for-new-messages/watch-imap-mailbox-for-new-messages.zip)

IMAP IDLE pushes inbox changes to your app.

```shell
dotnet add package RecursiveAI.OneMail.Client
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

```csharp
using RecursiveAI.OneMail.Client.Imap;
// args: host and port of a local test
// server that is already signed in.
var port = int.Parse(args[1]);
await using var client = await ImapClient
    .ConnectAsync(args[0], port);
var inbox = await client.SelectAsync(
    "INBOX");
var last = inbox.Exists;
var events = client.IdleAsync();
await foreach (var change in events)
{
    var total = inbox.Exists;
    if (change.Kind == ImapEventKind.Exists
        && total > last)
    {
        Console.WriteLine(
            $"New total: {total}");
        break;
    }
    last = total;
}
```

When the local server reports one new message in an empty inbox:

```text
New total: 1
```

Unzip [the example](https://recursiveai.org/onemail/cookbook/watch-imap-mailbox-for-new-messages/watch-imap-mailbox-for-new-messages.zip), then `dotnet run`.

For a mailbox that requires a password, add the import at the top and replace the `ConnectAsync` call and its declaration with the code below. Use the server’s implicit TLS port (usually 993) and set `user` and `password` from your app’s credentials. Keep the same `SelectAsync` and IDLE loop after login.

```csharp
using RecursiveAI.OneMail.Client.Protocol;

var tls = new ProtocolConnectionOptions { ImplicitTls = true };
await using var client = await ImapClient.ConnectAsync(args[0], port,
    new ImapClientOptions { Connection = tls });
await client.LoginAsync(user, password);
```

## The full program

Run the download as-is. It starts its own one-session server on loopback, with no account, password, or external server. The server greets the client with `PREAUTH` (already signed in), opens an empty `INBOX`, and sends `* 1 EXISTS` after `IDLE` begins. The client breaks out of the loop, which sends `DONE`. The server waits for `DONE`, acknowledges it, and then answers `NOOP` on the same connection.

```csharp
using System.Net;
using System.Net.Sockets;
using System.Text;
using RecursiveAI.OneMail.Client.Imap;

// Start a one-session, preauthenticated IMAP fixture on loopback only.
using var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
int port = ((IPEndPoint)listener.LocalEndpoint).Port;
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(10));
Task server = ServeInboxAsync(listener, timeout.Token);

var host = IPAddress.Loopback.ToString();
await using var client = await ImapClient.ConnectAsync(
    host, port, cancellationToken: timeout.Token);
var inbox = await client.SelectAsync("INBOX", cancellationToken: timeout.Token);
long previous = inbox.Exists;
await foreach (var change in client.IdleAsync(stop: timeout.Token))
{
    if (change.Kind == ImapEventKind.Exists && inbox.Exists > previous)
    {
        Console.WriteLine($"New total: {inbox.Exists}");
        break; // Leaves IDLE cleanly before the next command.
    }
    previous = inbox.Exists;
}
await client.NoopAsync(timeout.Token);
await server;
Console.WriteLine("IDLE ended; NOOP succeeded.");

static async Task ServeInboxAsync(TcpListener listener, CancellationToken stop)
{
    using var peer = await listener.AcceptTcpClientAsync(stop);
    using var wire = peer.GetStream();
    using var input = new StreamReader(wire, Encoding.ASCII, leaveOpen: true);

    async Task Send(string lines) => await wire.WriteAsync(
        Encoding.ASCII.GetBytes(lines.Replace("\n", "\r\n") + "\r\n"), stop);

    async Task<string> Read() => await input.ReadLineAsync(stop)
        ?? throw new EndOfStreamException();

    await Send("* PREAUTH [CAPABILITY IMAP4rev1 IDLE] Loopback fixture");
    while (true)
    {
        string[] parts = (await Read()).Split(' ', 3);
        string tag = parts[0];
        switch (parts[1])
        {
            case "CAPABILITY":
                await Send($"* CAPABILITY IMAP4rev1 IDLE\n{tag} OK CAPABILITY");
                break;
            case "SELECT":
                await Send($"* FLAGS (\\Seen)\n* 0 EXISTS\n* 0 RECENT\n" +
                    $"* OK [UIDVALIDITY 1]\n* OK [UIDNEXT 1]\n{tag} OK [READ-WRITE] SELECT");
                break;
            case "IDLE":
                await Send("+ idling\n* 1 EXISTS");
                if (await Read() != "DONE")
                    throw new InvalidOperationException("Expected DONE.");
                await Send($"{tag} OK IDLE ended");
                break;
            case "NOOP":
                await Send($"{tag} OK NOOP");
                return;
            default:
                throw new InvalidOperationException($"Unexpected command: {parts[1]}");
        }
    }
}
```

```text
New total: 1
IDLE ended; NOOP succeeded.
```

If the server doesn’t advertise IDLE support, `IdleAsync` throws `NotSupportedException`. The local fixture doesn’t use TLS; for a hosted mailbox, use the connection and sign-in steps in [Read email over IMAP](https://recursiveai.org/onemail/cookbook/read-email-over-imap/).

## Variations

Follow the notification with another command after the loop, not inside it. With `client` from the snippet at the top:

```csharp
await client.NoopAsync();
Console.WriteLine("IDLE ended; NOOP succeeded.");
```

## Related recipes

[Read email over IMAP](https://recursiveai.org/onemail/cookbook/read-email-over-imap/) · [Parse an EML file](https://recursiveai.org/onemail/cookbook/parse-eml/)

---

## The short answer

Select `INBOX`, record its message count, and consume `client.IdleAsync()`. When the server sends an `EXISTS` update and the count goes up, report new mail. To stop listening, leave the loop or cancel the `stop` token you passed to `IdleAsync`. The client sends `DONE` and reads the server’s completion before you reuse that connection.

## How do I get notified when I receive new email over IMAP in C#?

On a server that supports `IDLE`, watch the mailbox you selected with `SelectAsync`. The `EXISTS` number is the new total, not the number of arrivals and not a message ID. OneMail updates `inbox.Exists` before it yields the event. Compare that value with your last observed count: the initial count returned by `SelectAsync` describes messages already present and isn’t itself an arrival notification.

Other events can arrive in the same stream. An `Expunge` can reduce the count, so record the latest count even for events that aren’t `Exists`. A `Fetch` event can report changed flags rather than a delivery. If your app needs the actual messages, track which UIDs it has processed and use an IMAP search or fetch after leaving IDLE. The notification does not include the message body.

## How do I enable IMAP IDLE without blocking other mailbox commands?

There’s one active command per connection. Don’t start a search or fetch inside the `await foreach` on that same client. Stop IDLE cleanly first, run the command, and then enter IDLE again if you still want updates. The download uses `NOOP` as the next command so you can see where that boundary is without downloading a message.

For a service that keeps listening, pass your shutdown token as `stop`. According to the [IDLE documentation](https://recursiveai.org/onemail/docs/imap/#idle), OneMail renews IDLE every 29 minutes by default and ends the enumeration if the server sends `BYE`. A lifetime loop should therefore be prepared to reconnect and reselect the mailbox after a disconnect instead of treating the original connection as permanent.
