# Send Email in C# and .NET: API Tutorial

> Send email in C# with HttpClient and an email API instead of SmtpClient: a typed ASP.NET Core client with retries, templates, attachments and batches.

Canonical: https://www.cresca.xyz/blog/send-email-csharp
Author: Lalit Kumar Jangid
Published: 2026-10-27
Last updated: 2026-10-30

Microsoft's docs advise against `System.Net.Mail.SmtpClient` for new development, because it doesn't support many modern protocols. So to **send email in C#** today you either run MailKit over SMTP or drop SMTP and call an email API with `HttpClient`. This post takes the API route: one JSON request out, an email id back, delivery from your verified domain. It goes from a minimal call to a typed client managed by `IHttpClientFactory`, then templates, attachments and batches.

**TL;DR**

- `PostAsJsonAsync` to `https://api.cresca.xyz/api/v1/emails` with a bearer token.
- In ASP.NET Core, register a typed client with `AddHttpClient`.
- Network failures throw; API failures arrive as status codes. Retry 429, 5xx and `HttpRequestException` with an `Idempotency-Key`.
- Put template variables in a `Dictionary` so the JSON naming policy leaves them alone.

## What your .NET project needs

- **.NET 8 or later.** The client uses class primary constructors (C# 12) and only the base class library.
- **Cresca ready to send.** Your domain shows as verified in [Sending Domains](https://app.cresca.xyz/sending-domains), `hello@acme.com` (or similar) exists as a sender, and [API keys](https://app.cresca.xyz/api-keys) has issued you a *Sending access* key. If any of that is missing, the [email API quickstart](https://www.cresca.xyz/docs/quickstart) sets it up.
- **The key outside source control.** The `cr_live_` value appears only once. The console sample reads `CRESCA_API_KEY`. The ASP.NET Core version reads `Cresca:ApiKey` from configuration, which you fill with `dotnet user-secrets` on your machine and an environment variable named `Cresca__ApiKey` in production.

## Send email in C#: the basic request

```csharp
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;

using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(10) };
http.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", Environment.GetEnvironmentVariable("CRESCA_API_KEY"));

var response = await http.PostAsJsonAsync("https://api.cresca.xyz/api/v1/emails", new
{
    @from = "Acme <hello@acme.com>",
    to = "ana@example.com",
    subject = "Welcome to Acme",
    html = "<p>Hi Ana, your account is ready.</p>",
});

var body = await response.Content.ReadFromJsonAsync<JsonElement>();
if (!response.IsSuccessStatusCode)
{
    throw new Exception($"{body.GetProperty("name")}: {body.GetProperty("message")}");
}
Console.WriteLine(body.GetProperty("id").GetString());
```

Expect `200 OK` and `{"id": "4ef9a417-..."}`. `from` is a LINQ contextual keyword, so the anonymous type writes `@from`, which still serializes as `from`. And `PostAsJsonAsync` uses the web serializer defaults, which camel-case property names. Harmless for these lowercase names, but a template variable `NAME` would go out as `name`. That is why the template examples use a `Dictionary<string, object>`. Without a `text` property, Cresca generates the plain-text version for you.

A `new HttpClient` per call is fine for a one-off console tool. In a web app it can exhaust sockets, and one static instance never sees DNS changes. `IHttpClientFactory` fixes both.

## A typed C# client with retries

There's no official Cresca SDK for .NET, and you don't need one. `CrescaClient` takes an `HttpClient` in its constructor and leaves base address, timeout and auth to the registration. It adds three things:

- **Retries shaped by how .NET reports failure.** A dropped connection throws `HttpRequestException`. An expired `HttpClient.Timeout` throws `TaskCanceledException`, which the client tells apart from your own cancellation by checking `ct.IsCancellationRequested`. An error status throws nothing; you read `StatusCode`. The client retries network errors, timeouts, 429 `rate_limit_exceeded` and 5xx, waiting for `response.Headers.RetryAfter` if set and backing off exponentially if not. Other 4xx responses are thrown right away.
- **An `Idempotency-Key` header.** If Cresca accepted an email and the response never made it back, the retry presents the same key and Cresca returns its earlier answer instead of sending again. Cresca holds keys for 24 hours. Build keys from business data, like `$"welcome/{userId}"` or an invoice number; `Guid.NewGuid()` or `DateTime.UtcNow` would make every retry a fresh email. See [idempotency](https://www.cresca.xyz/docs/idempotency).
- **`CrescaException` with a `Name`.** The API's error JSON carries `statusCode`, a stable `name` such as `validation_error`, and a human-readable `message`. Catch `CrescaException` and test `Name` with an exception filter: `catch (CrescaException e) when (e.Name == "invalid_from_address")`. `Message` wording can change, so don't parse it.

```csharp
using System.Net.Http.Json;
using System.Text.Json;

/// <summary>A small client for the Cresca email API.</summary>
public sealed class CrescaClient(HttpClient http)
{
    private const int Attempts = 4;

    public async Task<JsonElement> PostAsync(
        string path, object payload, string? idempotencyKey = null, CancellationToken ct = default)
    {
        for (var attempt = 1; ; attempt++)
        {
            using var request = new HttpRequestMessage(HttpMethod.Post, path)
            {
                Content = JsonContent.Create(payload),
            };
            if (idempotencyKey is not null)
            {
                request.Headers.Add("Idempotency-Key", idempotencyKey);
            }

            HttpResponseMessage response;
            try
            {
                response = await http.SendAsync(request, ct);
            }
            catch (Exception e) when (e is HttpRequestException ||
                                      (e is TaskCanceledException && !ct.IsCancellationRequested))
            {
                // Network error or timeout: the idempotency key makes a retry safe.
                if (attempt == Attempts) throw;
                await Task.Delay(Backoff(attempt), ct);
                continue;
            }

            using (response)
            {
                var body = await ReadJsonAsync(response, ct);
                if (response.IsSuccessStatusCode) return body;

                var status = (int)response.StatusCode;
                var name = body.TryGetProperty("name", out var n) ? n.GetString() ?? "" : "unknown_error";
                var retryable = status >= 500
                    || (status == 429 && name != "monthly_quota_exceeded")
                    || name == "concurrent_idempotent_requests";
                if (!retryable || attempt == Attempts)
                {
                    var message = body.TryGetProperty("message", out var m) ? m.GetString() ?? "" : "";
                    throw new CrescaException(status, name, message);
                }
                await Task.Delay(response.Headers.RetryAfter?.Delta ?? Backoff(attempt), ct);
            }
        }
    }

    private static async Task<JsonElement> ReadJsonAsync(HttpResponseMessage response, CancellationToken ct)
    {
        try
        {
            return await response.Content.ReadFromJsonAsync<JsonElement>(ct);
        }
        catch (Exception e) when (e is JsonException or NotSupportedException)
        {
            // A proxy error may have no JSON body.
            return JsonSerializer.Deserialize<JsonElement>("{}");
        }
    }

    // 1s, 2s, 4s... plus up to 250 ms of jitter.
    private static TimeSpan Backoff(int attempt) =>
        TimeSpan.FromMilliseconds(1000 * Math.Pow(2, attempt - 1) + Random.Shared.Next(250));
}

public sealed class CrescaException(int status, string name, string message)
    : Exception($"{status} {name}: {message}")
{
    public int Status { get; } = status;
    public string Name { get; } = name;
}
```

Every attempt builds a new `HttpRequestMessage`, because `HttpClient` won't send the same message instance twice.

## Register it in ASP.NET Core

`AddHttpClient<CrescaClient>` turns it into a typed client: the factory gives each instance an `HttpClient` over pooled, recycled handlers. Keep the trailing slash on the base address and no leading slash on paths like `emails`. Without the trailing slash, `HttpClient` drops `v1` when it joins the two.

```csharp
using System.Net.Http.Headers;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddHttpClient<CrescaClient>(http =>
{
    http.BaseAddress = new Uri("https://api.cresca.xyz/api/v1/");
    http.Timeout = TimeSpan.FromSeconds(10);
    http.DefaultRequestHeaders.Authorization =
        new AuthenticationHeaderValue("Bearer", builder.Configuration["Cresca:ApiKey"]);
});

var app = builder.Build();

app.MapPost("/signup", async (SignupRequest signup, CrescaClient cresca) =>
{
    var userId = await CreateUserAsync(signup); // your own code

    await cresca.PostAsync("emails", new
    {
        to = signup.Email,
        template = new
        {
            id = "welcome",
            variables = new Dictionary<string, object> { ["NAME"] = signup.FirstName },
        },
    }, $"welcome/{userId}");

    return Results.Created($"/users/{userId}", null);
});

app.Run();

public record SignupRequest(string Email, string FirstName);
```

Typed clients are transient, so inject `CrescaClient` into endpoints, controllers or scoped services, never into a singleton. If you add a resilience handler to every client (Polly or `Microsoft.Extensions.Http.Resilience`), leave it off this one or drop the client's loop, since two retry layers multiply. The endpoint also awaits the send before replying. At higher volume, queue the email and let a hosted `BackgroundService` drain the queue.

## Send a template with variables

You can keep HTML out of your C# altogether. Design it once in Cresca's template editor with `{{{RESET_LINK}}}`\-style placeholders, publish it, and pass the alias plus a dictionary from code. This isn't Razor; Cresca does the rendering. Drafts stay private because sends use the *published* version, and values are HTML-escaped. If a key is missing from the dictionary and the template has no fallback, you get a `CrescaException` for 422 `validation_error` naming it. Read more in [templates and variables](https://www.cresca.xyz/docs/templates).

```csharp
await cresca.PostAsync("emails", new
{
    to = user.Email,
    template = new
    {
        id = "password-reset", // the template's alias or id
        variables = new Dictionary<string, object>
        {
            ["NAME"] = user.FirstName,
            ["RESET_LINK"] = resetUrl,
        },
    },
}, $"password-reset/{resetRequestId}");
```

## Add attachments

Attachments go inline in the JSON as base64. Load the file with `File.ReadAllBytesAsync` and encode it with `Convert.ToBase64String`. Cresca caps it at 20 files and 7 MB combined per email. The anonymous objects use `filename`, `content` and `content_type`; the last survives the naming policy because camel-casing only changes names that start with a capital. An inline image needs a `content_id` that your HTML references as `<img src="cid:logo">`. Cresca blocks executables like .exe and .js, and there's no attach-by-URL option yet.

```csharp
var pdf = await File.ReadAllBytesAsync("invoices/inv-2026-0042.pdf");

await cresca.PostAsync("emails", new
{
    @from = "Acme Billing <billing@acme.com>",
    to = customer.Email,
    subject = "Your invoice INV-2026-0042",
    html = "<p>Thanks for your payment. Your invoice is attached.</p>",
    attachments = new[]
    {
        new { filename = "inv-2026-0042.pdf", content = Convert.ToBase64String(pdf), content_type = "application/pdf" },
    },
}, "invoice/inv-2026-0042");
```

## Batch up to 100 emails with Chunk

`PostAsync("emails/batch", ...)` takes an array of at most 100 emails. Single-send fields all work there apart from `attachments` and `scheduled_at`. One invalid entry means nothing is sent, and the exception message gives that entry's zero-based index. The `data` array in the response lists ids in the order you sent, and the batch uses a single request of your rate limit.

```csharp
var emails = users.Select(u => new
{
    @from = "Acme <hello@acme.com>",
    to = u.Email,
    subject = "Your weekly summary",
    html = RenderSummary(u),
});

var index = 0;
foreach (var chunk in emails.Chunk(100))
{
    var result = await cresca.PostAsync("emails/batch", chunk, $"weekly-summary/2026-10-27/{index}");
    Console.WriteLine($"Batch {index}: {result.GetProperty("data").GetArrayLength()} emails accepted");
    index++;
}
```

`Enumerable.Chunk` (.NET 6 and later) hands back arrays of 100. The `Select` is lazy, so `RenderSummary` runs chunk by chunk as the loop pulls items. The chunk index in each key means a rerun inside the 24-hour window skips chunks Cresca already accepted. Encode user input in that HTML with `System.Net.WebUtility.HtmlEncode`, or use a template instead.

Requests-per-second limits by plan: Free 2, Professional 10, Premium 20, Ultra 50, Enterprise 100. Each email allows 50 recipients in total over to, cc and bcc, and every recipient is deducted from the monthly allowance as one email.

## SmtpClient, MailKit or an email API?

`SmtpClient` still compiles and runs, but it isn't recommended for new code. MailKit is the usual replacement and the right tool when there's an SMTP server to talk to. An HTTP API needs nothing past `HttpClient`, and you get typed errors and safe retries from the idempotency key. Cresca has no SMTP relay yet, so from .NET the API is the way in.

## Errors to handle when you send email in C#

How each common failure reaches your code. The [errors page](https://www.cresca.xyz/docs/errors) documents every name.

| Status | name or type | Cause | What your code sees |
| --- | --- | --- | --- |
| 403 | `invalid_from_address` | The sender isn't active, or its domain isn't verified. | `CrescaException`, no retry |
| 422 | `validation_error` | An invalid field or a missing template variable. | `CrescaException`, no retry |
| 422 | `missing_required_field` | to, from or subject missing, with no template to supply it. | `CrescaException`, no retry |
| 429 | `rate_limit_exceeded` | More requests per second than the plan allows. | Retried after Retry-After |
| 429 | `monthly_quota_exceeded` | The month's email allowance is gone. | `CrescaException`, no retry |
| 409 | `concurrent_idempotent_requests` | A request with this Idempotency-Key is still in flight. | Retried shortly |
| 5xx | `application_error` | Something failed inside Cresca. | Retried with backoff |
| none | `HttpRequestException` | Network failure on every attempt. | Rethrown after the fourth attempt |
| none | `TaskCanceledException` | `HttpClient.Timeout` expired on every attempt. | Rethrown after the fourth attempt |
| none | `OperationCanceledException` | Your `CancellationToken` was canceled. | Propagates at once |

Addresses on the suppression list (former hard bounces, complaints, unsubscribes) are silently left out and `PostAsync` still returns normally. See [suppression](https://www.cresca.xyz/docs/suppression).

## See whether the email was delivered

A successful `PostAsync` means Cresca accepted the email; inbox delivery is reported later. The [Transactional](https://app.cresca.xyz/transactional) screen shows each email's history. From code or a terminal, look it up by id; this needs a full-access key, because a sending key has no read rights:

```bash
curl https://api.cresca.xyz/api/v1/emails/4ef9a417-02e9-4d39-ad75-9611e0fcc33c \
  -H "Authorization: Bearer $CRESCA_API_KEY"
```

The `last_event` value progresses `queued`, `sent`, and finally `delivered` or `bounced`. The [email lifecycle](https://www.cresca.xyz/docs/email-lifecycle) page defines each status.

## C# and .NET questions

### Is SmtpClient deprecated?

It still works, but Microsoft's documentation says it isn't recommended for new development because it doesn't support many modern protocols, and it points to MailKit or other libraries instead. For new code, use MailKit if you have an SMTP server, or an email API over HTTPS.

### Why are my template variables not filled in?

System.Text.Json's web defaults camel-case property names, so `NAME` on an anonymous object is sent as `name` and doesn't match the template. Use a `Dictionary<string, object>` instead; its keys aren't renamed.

### Can I call the API from Blazor WebAssembly or a MAUI app?

Not directly. That code runs on the user's device, and any key shipped with it can be extracted. Keep the key server-side, call `CrescaClient` from an ASP.NET Core endpoint, and have the app call that. Blazor Server is fine, since it runs on the server.

## The same tutorial in other languages

[Node.js](https://www.cresca.xyz/blog/send-email-nodejs) · [Python](https://www.cresca.xyz/blog/send-email-python) · [PHP](https://www.cresca.xyz/blog/send-email-php) · [Go](https://www.cresca.xyz/blog/send-email-golang) · [Ruby](https://www.cresca.xyz/blog/send-email-ruby) · [Java](https://www.cresca.xyz/blog/send-email-java) · [Next.js](https://www.cresca.xyz/blog/send-email-nextjs) · [Laravel](https://www.cresca.xyz/blog/send-email-laravel) · [Django](https://www.cresca.xyz/blog/send-email-django) · [Ruby on Rails](https://www.cresca.xyz/blog/send-email-rails)

For request fields this post didn't use, the [send email API guide](https://www.cresca.xyz/blog/send-email-api) has each one with a cURL example. Read the [transactional email API overview](https://www.cresca.xyz/blog/transactional-email-api) for the whole flow, and [SMTP vs API](https://www.cresca.xyz/blog/smtp-vs-api-sending) is worth reading if MailKit is still on the table.

## Send your first email from .NET

Once your domain is verified and you hold a sending key, the console sample at the top sends a real email with `dotnet run`. **[Create a Cresca account](https://app.cresca.xyz/signup)**. It's free for 30 days: 250 contacts, 1,000 emails and 20 AI emails, no credit card. Transactional sends and campaigns share one allowance. The [quickstart](https://www.cresca.xyz/docs/quickstart) and [API docs](https://www.cresca.xyz/docs) pick up from here.
