Send with

Send email with C# and .NET

A typed HttpClient keeps the API key and base address in one place. The examples target .NET 8 and later.

Setup

dotnet user-secrets set "RobustEmail:ApiKey" "rb_test_..."

In production, set the environment variable RobustEmail__ApiKey instead.

A typed client

// RobustEmailClient.cs
using System.Net.Http.Json;
using System.Text.Json;

public sealed class RobustEmailClient(HttpClient http)
{
    /// <summary>Sends one email and returns its ID.</summary>
    public async Task<string> SendAsync(object email, string? idempotencyKey = null, CancellationToken ct = default)
    {
        using var request = new HttpRequestMessage(HttpMethod.Post, "emails")
        {
            Content = JsonContent.Create(email),
        };
        if (idempotencyKey is not null)
        {
            request.Headers.Add("Idempotency-Key", idempotencyKey);
        }

        using var response = await http.SendAsync(request, ct);
        var body = await response.Content.ReadFromJsonAsync<JsonElement>(ct);
        if (!response.IsSuccessStatusCode)
        {
            throw new InvalidOperationException(
                $"{body.GetProperty("name").GetString()}: {body.GetProperty("message").GetString()}");
        }

        return body.GetProperty("id").GetString()!;
    }
}

Register it and send

// Program.cs
using System.Net;
using System.Net.Http.Headers;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddHttpClient<RobustEmailClient>(client =>
{
    client.BaseAddress = new Uri("https://robustemail.com/api/v2/");
    client.DefaultRequestHeaders.Authorization =
        new AuthenticationHeaderValue("Bearer", builder.Configuration["RobustEmail:ApiKey"]);
    client.Timeout = TimeSpan.FromSeconds(15);
});

var app = builder.Build();

app.MapPost("/signup", async (SignupRequest input, RobustEmailClient email) =>
{
    var user = await CreateUserAsync(input); // your own code

    var id = await email.SendAsync(new
    {
        @from = "Acme <hello@acme.com>",
        to = new[] { user.Email },
        subject = "Welcome to Acme",
        html = $"<p>Hi {WebUtility.HtmlEncode(user.Name)}, thanks for signing up.</p>",
    }, $"welcome-user-{user.Id}");

    return Results.Created($"/users/{user.Id}", new { emailId = id });
});

app.Run();

record SignupRequest(string Email, string Name);

@from is written with @ because from is a C# keyword in queries; the JSON field is still from. Field names such as reply_to and content_type are sent exactly as written.

Attachments

var pdf = Convert.ToBase64String(await File.ReadAllBytesAsync("invoice-2041.pdf"));

await email.SendAsync(new
{
    @from = "Acme Billing <billing@acme.com>",
    to = new[] { "jane@example.com" },
    subject = "Your invoice #2041",
    html = "<p>Your invoice is attached.</p>",
    attachments = new[]
    {
        new { filename = "invoice-2041.pdf", content = pdf, content_type = "application/pdf" },
    },
}, "invoice-2041");

Next