Menu C# / .NET

SDKs

C# and .NET SDK

The official client of the fake-email.pro API for .NET 8 and later, async throughout and with no dependencies beyond HttpClient and System.Text.Json. It covers every endpoint with typed models, turns errors into exceptions you can catch by type, retries rate limits on its own, and waits for the email of an end-to-end test – handing back its one-time code or confirmation link. Open source under the MIT license.

.NET 8+, async with CancellationToken, no dependencies; xUnit, NUnit and Playwright

Terminal
dotnet add package FakeEmailPro

FakeEmailPro on NuGetSource on GitHub

API key

Create a key as in Quickstart and put it in the FAKE_EMAIL_API_KEY environment variable – a CI secret on a build agent. The client reads it from there, or takes it as ApiKey in FakeEmailClientOptions. The API is server-to-server, without CORS: call it from the test process, never from the page under test or a Blazor WebAssembly app.

Quickstart

C#
using FakeEmailPro;

using var client = new FakeEmailClient(); // reads FAKE_EMAIL_API_KEY

var mailbox = await client.Mailboxes.CreateAsync();
Console.WriteLine($"Sign up with {mailbox.Address}");

try
{
    // Long-polls the mailbox for up to 60 s and returns the one-time code
    var code = await client.WaitForCodeAsync(mailbox.Address, new WaitOptions { Subject = "verification" });
    Console.WriteLine(code);
}
finally
{
    await client.Mailboxes.DeleteAsync(mailbox.Address);
}

xUnit, NUnit and Playwright

FakeEmailClient is thread-safe: one static instance serves the whole run, while each test gets a fresh mailbox from the setup of the Playwright PageTest base class. WaitForCodeAsync and WaitForLinkAsync wait across as many long polls as their timeout allows; keep the test timeout above it.

// packages: FakeEmailPro, Microsoft.Playwright.Xunit
using FakeEmailPro;
using Microsoft.Playwright;
using Microsoft.Playwright.Xunit;

public class SignupTests : PageTest
{
    private static readonly FakeEmailClient Mail = new(); // FAKE_EMAIL_API_KEY from the environment
    private string _inbox = "";

    // A fresh mailbox for every test, deleted when the test ends
    public override async Task InitializeAsync()
    {
        await base.InitializeAsync();
        _inbox = (await Mail.Mailboxes.CreateAsync()).Address;
    }

    public override async Task DisposeAsync()
    {
        await Mail.Mailboxes.DeleteAsync(_inbox);
        await base.DisposeAsync();
    }

    [Fact]
    public async Task Signs_up_with_an_email_code()
    {
        await Page.GotoAsync("https://your-app.example/signup");
        await Page.GetByLabel("Email").FillAsync(_inbox);
        await Page.GetByRole(AriaRole.Button, new() { Name = "Send code" }).ClickAsync();

        var code = await Mail.WaitForCodeAsync(_inbox, new WaitOptions { Subject = "verification" });

        await Page.GetByLabel("Code").FillAsync(code);
        await Page.GetByRole(AriaRole.Button, new() { Name = "Continue" }).ClickAsync();
        await Expect(Page.GetByText("Welcome")).ToBeVisibleAsync();
    }
}

Waiting for an email

  • WaitForMessageAsync(address, options) – the first message that matches From, Subject and an optional Match function of WaitOptions. It repeats the 60-second long poll until Timeout (60 s by default), then throws WaitTimeoutException.
  • WaitForCodeAsync and WaitForLinkAsync – the same, returning the code or the confirmation link the API read out of the email; a message without one is skipped.
  • For the next email in the same mailbox, pass After with the id of the one you have. More on the flow in Email testing.
  • A CancellationToken, the last argument of every method, stops a wait early with an OperationCanceledException, as everywhere in .NET.
C#
var first = await client.WaitForMessageAsync(address, new WaitOptions { Subject = "Welcome" });

// Strictly after the first one: nothing that arrived in between is lost
var second = await client.WaitForMessageAsync(address, new WaitOptions
{
    After = first.Id,
    Match = message => message.AttachmentsCount > 0,
});

Methods and models

Every method is async and takes a CancellationToken as its last argument. ListAllAsync is an IAsyncEnumerable over every page for await foreach; models are immutable records with DateTimeOffset timestamps.

The client has a method for each endpoint of the API; their parameters and responses are in Endpoints.

Errors and retries

Every error of the API is thrown as an APIError with the HTTP status, the error code, the message and the rate-limit headers; its subclass names the case: BadRequestError 400, AuthenticationError 401, QuotaExhaustedError 402, PermissionDeniedError 403, NotFoundError 404, ConflictError 409, RateLimitError 429, InternalServerError 5xx. What each status and code means is in Errors. A request that got no response throws APIConnectionError, and one whose HTTP attempt outlasted its timeout APITimeoutError, a subclass of it.

Retries (twice by default) wait the Retry-After of the response, or a short backoff without one. A 429 and a 503 are retried on every method, since the server refused them before doing anything – except a 503 that asks to come back in more than 5 s, which is thrown at once. A network error, a timed-out attempt, a 502, a 504 and Cloudflare's 520–524 are retried on GET and DELETE only, so a mailbox is never created twice; a retried DELETE that gets 404 counts as done, since the attempt before it went through. A wait helper waits out 429, 502–504, 520–524 and connection errors until its own deadline, and then throws WaitTimeoutError.

In .NET the names end in Exception: APIError is ApiException, NotFoundError is NotFoundException, InternalServerError is InternalServerErrorException, and so on, all under FakeEmailException; no response at all is an ApiConnectionException, and an HTTP attempt past its timeout an ApiTimeoutException. AuthenticationException shares its name with the one in System.Security.Authentication – write FakeEmailPro.AuthenticationException if both namespaces are imported.

Configuration

C#
using var client = new FakeEmailClient(new FakeEmailClientOptions
{
    ApiKey = "fep_...",                      // default: the FAKE_EMAIL_API_KEY environment variable
    BaseUrl = "https://api.fake-email.pro",  // default
    Timeout = TimeSpan.FromSeconds(30),      // per HTTP attempt; a wait request always gets its server timeout + 10 s
    MaxRetries = 2,                          // 0 disables retries
    UserAgent = "my-e2e-suite/1.0",          // appended to fake-email-pro-dotnet/<version>
    HttpClient = httpClient,                 // optional; stays yours to dispose
});

Without an HttpClient the client creates and owns one: dispose the FakeEmailClient to release it. One from IHttpClientFactory needs its Timeout at Timeout.InfiniteTimeSpan, since the SDK times each attempt itself and a wait is held up to 60 s. client.WithOptions(new RequestOptions { ... }) gives a view with another timeout or retry count that shares the connections. A shorter timeout there never cuts a wait short: a long poll always gets its server timeout + 10 s.

Other languages

Go, Java, JavaScript / TypeScript, PHP, Python – or every SDK and the OpenAPI document for any other language.

Something missing, confusing or wrong on this page? Tell us