How to Receive Email in C#: Read the Inbox, Save Attachments and Get New Mail Pushed

Receive email in C# and read it with one awaited call: create an address, wait for a message, save attachments, and handle new mail in an ASP.NET Core webhook.

By · · 12 min read

C# code that reads the newest message in a Mailcycle inbox with the .NET SDK

You want to receive email in C#: read a supplier’s invoice and save the PDF, pick a sign-in code out of a verification email in a test, or hand a customer’s reply to your app. The usual route is MailKit’s ImapClient: connect to a mailbox, search it, fetch a MimeMessage and walk its parts. That fits when you already have a mailbox and its credentials. If what you want is “give my code an address and let it read what arrives”, an email API is shorter.

This tutorial shows how to receive and read email in C# with Mailcycle’s .NET SDK, the Mailcycle NuGet package. You’ll create an address, list and open messages, save attachments to disk, await the next email, and then get new mail pushed to an ASP.NET Core minimal API by webhook.

It is the receiving half of How to send email from C# and an ASP.NET Core Web API, which covers sending, HTML, attachments you send and threaded replies. This one goes deep on the inbox.

Quick answer: how to receive email in C#

Install the package, sign in with your recovery phrase, create an address, and await WaitForAsync. It returns when a message arrives, parsed and decrypted, with the sender, subject, text, HTML and attachments as plain properties.

dotnet add package Mailcycle
using Mailcycle;

using var mc = await MailcycleClient.SignInAsync(
    Environment.GetEnvironmentVariable("MAILCYCLE_PHRASE")!);

var address = await mc.Addresses.CreateAsync(new NewAddress
{
    Prefix = "inbound",
    Label = "C# inbox",
});
Console.WriteLine($"Send an email to {address.EmailAddress}");

var message = await mc.Messages.WaitForAsync(new WaitFor
{
    AddressId = address.Id,
    Timeout = TimeSpan.FromMinutes(5),
});
Console.WriteLine($"{message.FromAddress}: {message.Subject}");
Console.WriteLine(message.Text);

Run it, send an email to the address it prints from any mail app, and the program prints what you sent. The rest of this guide is what a real app needs around that: paging, attachments, push and errors.

Flow: a sender writes to your address, Mailcycle encrypts the mail on arrival, the .NET SDK lists, waits for or receives it by webhook, and your C# code reads the message
Mail sent to a Mailcycle address is encrypted on arrival, then your C# code reads it with the .NET SDK, by waiting for it or from a webhook.

Prerequisites

  • .NET 8 SDK or later. Check with dotnet --version.
  • A Mailcycle account. Receiving works on every plan when your code signs in with the recovery phrase. API keys and webhooks start at Operator. Pricing has the plans.
  • Your recovery phrase, in an environment variable named MAILCYCLE_PHRASE, for any process that opens mail.
  • ASP.NET Core, only for the webhook section.

Step 1: Add the NuGet package

dotnet add package Mailcycle

Every call is async and takes an optional CancellationToken. The client implements IDisposable, so using var mc = ... closes it when you are done. In a web app, build it once at start-up and register it as a singleton.

Step 2: Sign in and create an address

MailcycleClient.SignInAsync(phrase) works on every plan. With an Operator plan or above you can also use an API key:

using Mailcycle;

var phrase = Environment.GetEnvironmentVariable("MAILCYCLE_PHRASE")!;
var apiKey = Environment.GetEnvironmentVariable("MAILCYCLE_API_KEY");

using var mc = apiKey is null
    ? await MailcycleClient.SignInAsync(phrase)
    : await MailcycleClient.WithApiKeyAsync(apiKey, phrase);

An address that receives mail needs a public key the mail server can encrypt to. Addresses.CreateAsync() derives that key from your phrase and uploads only the public half, so it needs a client built with the phrase.

var address = await mc.Addresses.CreateAsync(new NewAddress
{
    Prefix = "invoices",
    Label = "Supplier invoices",
    RetentionDays = 30,
});
Console.WriteLine($"{address.EmailAddress} {address.Id}");

foreach (var existing in await mc.Addresses.ListAsync())
{
    Console.WriteLine($"{existing.EmailAddress} {existing.Label} receives={existing.Receives}");
}

The options on NewAddress:

  • Prefix = "invoices" gives invoices- plus a random ending on a shared domain.
  • Style (NameStyle) rolls a name in that style, and mc.Addresses.RollNamesAsync(style) lists some to choose from.
  • LocalPart asks for an exact name. Any name you type needs Scale or above, and so does Domain with your own domain.
  • Label is encrypted on your machine, so the server stores it as ciphertext.
  • RetentionDays is 1 to 90, and 7 by default.

Save the ibx_... id in address.Id: every reading call takes it.

Step 3: List and read emails in the inbox

ListAsync returns one page of a folder, newest first:

var page = await mc.Messages.ListAsync(address.Id, limit: 20);
foreach (var message in page.Messages)
{
    var flag = message.Read ? " " : "*";
    Console.WriteLine($"{flag} {message.ReceivedAt} {message.FromAddress} {message.Subject}");
}

if (page.NextCursor is not null)
{
    var older = await mc.Messages.ListAsync(address.Id, limit: 20, cursor: page.NextCursor);
    Console.WriteLine($"{older.Messages.Count} older messages on the next page");
}

limit goes up to 200. NextCursor is opaque: pass it back as cursor as it came. To walk a whole folder, AllAsync pages for you:

var all = await mc.Messages.AllAsync(address.Id);
var invoices = all
    .Where(m => m.Subject.Contains("invoice", StringComparison.OrdinalIgnoreCase) && m.Attachments.Count > 0)
    .ToList();
Console.WriteLine($"{invoices.Count} invoices with files attached");

Message content is encrypted, so you decrypt and then filter in C#, as above. Pass folder: "sent", "junk", "trash" or "starred" to read another folder.

What is in a Message

Each Message is an immutable record, already parsed from MIME and decrypted:

Property What it holds
Id, AddressId The message’s msg_... id and the address it arrived at.
ReceivedAt When it arrived, as an ISO 8601 string in UTC.
FromAddress, FromName The sender’s address and display name.
ReplyTo Where a reply should go: the Reply-To header if set, otherwise From.
To, Subject The recipient and the subject line.
Text The plain-text body.
Html The HTML body exactly as sent. Do not render this one.
SafeHtml The HTML with remote images, trackers and embeds removed.
Attachments A list of Attachment: Index, Filename, MimeType, Size, ContentId, Stored.
MessageId The sender’s Message-ID header, used to thread a reply.
Read, Starred, Folder The message’s state.
Opened false if it could not be decrypted: no phrase, or the wrong one.

A message that does not open comes back with Opened set to false and empty content rather than throwing, so one bad message never hides the rest of a page.

Read the email body in C#: Text, Html and SafeHtml

Most mail carries a plain-text and an HTML part. Use Text for anything you parse, such as codes, order numbers or a reply to hand to a model. If you show the HTML anywhere, use SafeHtml:

var message = await mc.Messages.GetAsync("msg_91be02c4a7d1");

if (!message.Opened)
{
    throw new InvalidOperationException("This message did not open: check the recovery phrase.");
}

Console.WriteLine(string.IsNullOrEmpty(message.Text) ? "(no plain-text part)" : message.Text);

if (!string.IsNullOrEmpty(message.SafeHtml))
{
    await File.WriteAllTextAsync("preview.html", message.SafeHtml);
    Console.WriteLine($"{message.Blocked.Count} remote items taken out");
}

GetAsync fetches one message by id, from any folder. SafeHtml is the HTML the Mailcycle apps show: remote images, tracking pixels and embeds are taken out, so opening it does not tell the sender when you read it. If you embed it in a page of your own, put it in a sandboxed <iframe>.

Download email attachments in C#

Attachments are listed on the message and fetched one at a time. Their bodies are encrypted like the message, and AttachmentAsync opens them on your machine. This helper saves a message’s files safely:

static string SafeName(string filename)
{
    var name = Path.GetFileName(filename.Replace('\\', '/'));
    foreach (var bad in Path.GetInvalidFileNameChars())
    {
        name = name.Replace(bad, '_');
    }
    return string.IsNullOrWhiteSpace(name) ? "attachment" : name;
}

static async Task<List<string>> SaveAttachmentsAsync(
    MailcycleClient mc, Message message, string folder, bool inline = false)
{
    var target = Path.Combine(folder, message.Id);
    var saved = new List<string>();
    foreach (var attachment in message.Attachments)
    {
        if (!attachment.Stored) continue;                          // an empty part: nothing to fetch
        if (attachment.ContentId is not null && !inline) continue; // an image the HTML shows inline

        var bytes = await mc.Messages.AttachmentAsync(message, attachment.Index); // opened on this machine
        Directory.CreateDirectory(target);
        var path = Path.Combine(target, $"{attachment.Index}-{SafeName(attachment.Filename)}");
        await File.WriteAllBytesAsync(path, bytes);
        saved.Add(path);
    }
    return saved;
}

Then process every unread message that has files, and mark each one read so the next run skips it:

foreach (var message in await mc.Messages.AllAsync(address.Id))
{
    if (message.Read || message.Attachments.Count == 0) continue;

    foreach (var path in await SaveAttachmentsAsync(mc, message, "downloads"))
    {
        Console.WriteLine($"saved {path}");
    }
    await mc.Messages.MarkReadAsync(message.Id);
}

The details that matter with real mail:

  • The file name comes from the sender. A name like ../../appsettings.json is a classic path-traversal trick. SafeName keeps the last path component and replaces characters the file system rejects, and the index prefix keeps two files called invoice.pdf apart.
  • Stored is false for a part that had no body. Skip it.
  • ContentId marks an inline image, the kind HTML shows with <img src="cid:logo">. Most pipelines want the PDF, not the logo.
  • MimeType and Size let you keep only application/pdf, or refuse anything over a size, before you download it.
  • Treat files as untrusted. Scan them, or open them in a sandbox, before anything else touches them.

That is the job a C# email parser does for attachments, without walking a MIME tree or decoding base64.

Wait for the next email in C#

WaitForAsync returns when a matching message arrives, opened. It is the shortest way to read a verification email in an end-to-end test, or to wait for a reply:

using System.Text.RegularExpressions;

var started = DateTimeOffset.UtcNow; // take the time before the email is triggered

// ...trigger the email here: submit a sign-up form, call your own API...

try
{
    var message = await mc.Messages.WaitForAsync(new WaitFor
    {
        AddressId = address.Id,
        Subject = "verify",
        Since = started,
        Timeout = TimeSpan.FromSeconds(120),
    });

    var match = Regex.Match(message.Text, @"\b(\d{6})\b");
    Console.WriteLine(match.Success ? $"code: {match.Groups[1].Value}" : $"No code in: {message.Text}");
}
catch (ApiException error) when (error.Code == "timeout")
{
    Console.WriteLine("No verification email within two minutes.");
}

How it behaves:

  • Since is the important one. Mail received from that moment on counts, even if it landed before the wait began. Take the time before you trigger the email, so a fast delivery cannot slip past. It defaults to now.
  • From and Subject match text the sender or subject contains, ignoring case. AddressId limits the wait to one address.
  • Timeout is 60 seconds by default. When it runs out you get an ApiException with Code set to timeout.
  • PollEvery (five seconds by default) is how often it checks when the live stream is not available.
  • A CancellationToken passed as the second argument stops the wait when your test run is cancelled.

For a test suite, give each test its own address and delete it afterwards with mc.Addresses.DeleteAsync(address.Id). In an xUnit fixture that is an IAsyncLifetime with CreateAsync in InitializeAsync and DeleteAsync in DisposeAsync.

Mark as read, star, move and delete

These calls change state only, so they do not open any content:

Call What it does
mc.Messages.MarkReadAsync(id) Marks read. MarkReadAsync(id, false) marks unread.
mc.Messages.StarAsync(id) Stars it. StarAsync(id, false) unstars.
mc.Messages.MoveToAsync(id, "junk") Moves to "inbox", "junk" or "trash".
mc.Messages.RestoreAsync(id) Takes a message back out of the trash.
mc.Messages.DeleteAsync(id) Deletes it now.
mc.Messages.EmptyTrashAsync() Deletes everything in the trash and returns how many.

Get new email pushed to ASP.NET Core with a webhook

Mailcycle can tell your code the moment mail arrives. A message.received event carries the message’s id and its address’s id. Your code fetches the message by id and opens it locally, so the phrase stays on your machine.

Add a webhook in the app under API, on the Webhooks tab, or from C# with a signed-in session:

var created = await mc.Webhooks.CreateAsync(
    "https://example.com/hooks/mailcycle",
    ["message.received"],
    "Inbound mail");
Console.WriteLine(created.Secret); // whsec_..., shown once: store it as MAILCYCLE_WEBHOOK_SECRET

The URL must be HTTPS. For local development, expose your dev server through a tunnel. Then the receiving route, in Program.cs:

using System.Collections.Concurrent;
using System.Text.Json.Nodes;
using Mailcycle;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton(await MailcycleClient.SignInAsync(
    Environment.GetEnvironmentVariable("MAILCYCLE_PHRASE")!));
var app = builder.Build();

var secret = Environment.GetEnvironmentVariable("MAILCYCLE_WEBHOOK_SECRET")!;
var seen = new ConcurrentDictionary<string, bool>(); // one process only: use a table with a unique key in production

app.MapPost("/hooks/mailcycle", async (HttpRequest request, MailcycleClient mc) =>
{
    using var reader = new StreamReader(request.Body);
    var raw = await reader.ReadToEndAsync(); // the exact body, before any parsing

    if (!WebhookSignature.VerifyNow(secret, raw, request.Headers["Mailcycle-Signature"]))
        return Results.Unauthorized();

    var eventId = request.Headers["Mailcycle-Event-Id"].ToString();
    if (eventId.Length > 0 && !seen.TryAdd(eventId, true))
        return Results.NoContent(); // a retry of an event already handled

    var ev = JsonNode.Parse(raw)!;
    if ((string?)ev["type"] == "message.received")
    {
        var message = await mc.Messages.GetAsync((string)ev["payload"]!["messageId"]!);
        if (message.Opened)
        {
            var saved = await SaveAttachmentsAsync(mc, message, "downloads");
            Console.WriteLine($"{message.FromAddress}: {message.Subject} ({saved.Count} files)");
            await mc.Messages.MarkReadAsync(message.Id);
        }
    }
    return Results.NoContent();
});

app.Run();

SaveAttachmentsAsync is the helper from the attachments section. What each part is for:

  • The signature is an HMAC-SHA256 of the timestamp and the raw body, keyed with your whsec_ secret. VerifyNow checks it in constant time and refuses a timestamp more than five minutes old. Check the body as it arrived: a body that was parsed and re-serialised will not match.
  • Answer fast. Mailcycle waits 10 seconds for a 2xx. For slow work, put the message id on a queue, such as a Channel<string> read by a BackgroundService, and return right away.
  • Deduplicate. An event can arrive more than once, and Mailcycle-Event-Id is the same on every attempt. The dictionary suits one process. With several instances, insert the id into a table with a unique constraint.
  • Azure Functions and Worker Services follow the same steps: read the raw body, verify, fetch by id.

You can test the route without a live webhook. WebhookSignature.Header(secret, body, timestamp) builds the header Mailcycle would send. Retries, the delivery log and every event type are in the webhooks guide, and Receive email with a webhook walks through the receiver in more depth.

MailKit and an email API in C#

MailKit’s ImapClient connects to a mailbox: you give it a host, port 993 and credentials, select the inbox, search, and read each MimeMessage. Gmail and Microsoft 365 generally expect OAuth 2.0 or an app password for that connection. It is the right tool when the mail already lives in a mailbox you own, like a shared support inbox, and your code needs to read it where it is.

An email API fits when your code needs addresses of its own: one per customer, per test run or per agent, created in code, with mail pushed to you as it arrives.

MailKit ImapClient Mailcycle .NET SDK
Install dotnet add package MailKit dotnet add package Mailcycle
You need An IMAP mailbox and its credentials A recovery phrase, plus an API key if you want one
New addresses Made at your mail provider mc.Addresses.CreateAsync() in code
Parsing MimeMessage parts Parsed properties: Text, Html, Attachments
Tracker-free HTML Strip it yourself SafeHtml, with Blocked listing what was removed
Attachments Walk Attachments, MimePart.Content mc.Messages.AttachmentAsync(message, index)
New-mail push IMAP IDLE Webhooks and the event stream
Wait for one email Write the loop yourself WaitForAsync()
Mail at rest Depends on the provider Encrypted with keys from your recovery phrase

Run the receiver as a BackgroundService

An ASP.NET Core app often needs a loop that watches an address for as long as the process lives. A BackgroundService fits, because the host passes it a CancellationToken that fires on shutdown, and every call in the SDK accepts one. Register the client once as a singleton so the whole app shares one signed-in session.

builder.Services.AddSingleton(_ =>
    MailcycleClient.SignInAsync(builder.Configuration["Mailcycle:Phrase"]!).GetAwaiter().GetResult());
builder.Services.AddHostedService<InvoiceWatcher>();

public sealed class InvoiceWatcher(MailcycleClient mc, ILogger<InvoiceWatcher> log) : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stop)
    {
        var since = DateTimeOffset.UtcNow;
        while (!stop.IsCancellationRequested)
        {
            try
            {
                var message = await mc.Messages.WaitForAsync(
                    new WaitFor { Subject = "invoice", Since = since, Timeout = TimeSpan.FromMinutes(5) }, stop);
                since = DateTimeOffset.Parse(message.ReceivedAt);
                log.LogInformation("Invoice from {From}", message.FromAddress);
            }
            catch (ApiException e) when (e.Code == "timeout") { /* nothing arrived, wait again */ }
        }
    }
}

Keep the phrase in user secrets or your host’s secret store through IConfiguration, never in appsettings.json. The timeout code is the normal quiet case, so the loop catches it and starts the next wait.

An xUnit fixture with IAsyncLifetime

xUnit builds a test class once per test, and IAsyncLifetime gives you an async setup and teardown pair. Create the address in InitializeAsync and delete it in DisposeAsync, so a failing assertion never leaves an inbox behind.

public sealed class SignupEmailTests : IAsyncLifetime
{
    private MailcycleClient _mc = default!;
    private Address _address = default!;

    public async Task InitializeAsync()
    {
        _mc = await MailcycleClient.SignInAsync(Environment.GetEnvironmentVariable("MAILCYCLE_PHRASE")!);
        _address = await _mc.Addresses.CreateAsync(new NewAddress { Prefix = "xunit", RetentionDays = 1 });
    }

    public async Task DisposeAsync()
    {
        await _mc.Addresses.DeleteAsync(_address.Id);
        _mc.Dispose();
    }
}

Put WebApplicationFactory<Program> in the same class to drive your own API in memory, post the sign-up with _address.EmailAddress, and assert on the message the wait returns.

Parallel waits with Task.WhenAll

Because every call is a Task, you can create several addresses and wait on them together. await Task.WhenAll(addresses.Select(a => mc.Messages.WaitForAsync(new WaitFor { AddressId = a.Id, Timeout = TimeSpan.FromMinutes(1) }))) returns once every address has its message, and the first failure surfaces from the awaited task. Use SemaphoreSlim to cap how many run at once if you start hundreds.

Dependency injection and options in ASP.NET Core

The client is built asynchronously, so register it with an async factory rather than blocking at start-up. A small hosted service or a Lazy<Task<MailcycleClient>> registered as a singleton lets the first request pay the sign-in cost without blocking the thread pool during Program.cs. MailcycleOptions sets the API address and the request timeout, which is useful when you point a test host at a different environment. Keep one instance per process: each SignInAsync opens a 30-day session, and ResumeAsync with the saved token avoids signing in on every restart.

For integration tests with WebApplicationFactory<Program>, replace the registration in ConfigureTestServices with a client signed in to a test account. The factory then runs your real controllers in memory, the sign-up email travels over the real provider, and WaitForAsync reads it from the address the test created.

Troubleshooting

  • A wait hangs when the pod restarts. Pass the host’s CancellationToken into every call, so a deploy cancels the wait cleanly. Log the message id and address id, never the body.
  • A test client sees the wrong account. Inject MailcycleClient rather than building it where you use it, so tests can pass one signed in to a test account.
  • Messages have Opened set to false and empty fields. The client has no phrase, or a phrase from a different account. Build it with SignInAsync(phrase).
  • Nothing arrives at a new address. Check address.Receives in mc.Addresses.ListAsync(), and check the sender used the exact address, since prefixed names have a random ending.
  • ApiException with Code of rate_limited (429). You are reading too much too fast. Back off, read only what is new, or switch to webhooks.
  • A 404 fetching an attachment. The part has Stored set to false. Skip it.
  • The webhook route returns 401 for real deliveries. You are verifying a parsed body, or the wrong secret. Use the raw request body and the whsec_ secret of this webhook.

Every error code is listed in Errors.

Reply from C#, or hand the inbox to an agent

To answer a message in the same thread, pass it as ReplyTo on an Outgoing and call mc.Messages.SendAsync(). Sending email from C# covers that, along with the plans that send.

If an AI agent should read the inbox, Mailcycle also runs as an MCP server with tools such as wait_for_message, read_message and read_attachment, for Claude Code, Cursor, Codex or any other MCP client. Start with Give your AI agent its own email inbox.

Next steps

FAQ

How do I receive email in C#?

Give your code an address that receives mail, then read it with a client. With Mailcycle, run dotnet add package Mailcycle, sign in with MailcycleClient.SignInAsync(phrase), create an address with mc.Addresses.CreateAsync(), and await mc.Messages.WaitForAsync(). The message comes back parsed and decrypted: sender, subject, text, HTML and attachments.

How do I read emails from an inbox in C#?

Call mc.Messages.ListAsync(addressId) for one page, newest first, or mc.Messages.AllAsync(addressId) to walk the whole folder. Each Message has FromAddress, Subject, Text, SafeHtml, Attachments and Read. Pass folder: "junk", "trash", "sent" or "starred" to read another folder.

How do I download email attachments in C#?

Each Message lists its files in message.Attachments, with Filename, MimeType, Size and Index. Call mc.Messages.AttachmentAsync(message, attachment.Index) to get a byte[], opened on your machine, and write it with File.WriteAllBytesAsync. Clean the file name first, because it comes from the sender.

How can a C# app wait for a new email?

Await mc.Messages.WaitForAsync(new WaitFor { AddressId = ..., Subject = ..., Since = ..., Timeout = ... }). It returns the first matching message. If nothing matches in time it throws an ApiException with Code set to timeout, and a CancellationToken stops the wait early.

How do I get notified when an email arrives in an ASP.NET Core app?

Add a webhook for message.received, point it at a minimal API route, and check each delivery with WebhookSignature.VerifyNow() against the raw body. The event carries the message id, so fetch the message with mc.Messages.GetAsync(). Webhooks are on the Operator plan and above.

Can I receive email in C# without an IMAP mailbox?

Yes. Mailcycle addresses receive mail directly, and your code reads it over HTTPS. There is no IMAP host, port or mailbox password.

Which Mailcycle plan do I need to receive email from C#?

Every plan can create addresses, read mail and download attachments when the code signs in with the recovery phrase. API keys and webhooks start at Operator. See Plans and limits.

Why does the C# client need my recovery phrase?

Mail is encrypted the moment it arrives, with keys from your recovery phrase. The .NET client derives the same keys on your machine and opens each message in your process. A message that does not open comes back with Opened set to false.

Receive email in code