Skip to main content

Send an email

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

var client = new HttpClient();
client.DefaultRequestHeaders.Authorization =
    new AuthenticationHeaderValue("Bearer", "snd_your_api_key");

var payload = new
{
    from = "you@yourdomain.com",
    to = new[] { "user@example.com" },
    subject = "Hello from Sendi",
    html = "<p>It just works.</p>"
};

var content = new StringContent(
    JsonSerializer.Serialize(payload),
    Encoding.UTF8,
    "application/json"
);

var response = await client.PostAsync("https://app.usesendi.com/api/emails", content);
var body = await response.Content.ReadAsStringAsync();

Console.WriteLine(body);

With dependency injection

// Program.cs
builder.Services.AddHttpClient("Sendi", client =>
{
    client.BaseAddress = new Uri("https://app.usesendi.com/api/");
    client.DefaultRequestHeaders.Authorization =
        new AuthenticationHeaderValue("Bearer", builder.Configuration["Sendi:ApiKey"]);
});

// EmailService.cs
public class EmailService
{
    private readonly HttpClient _client;

    public EmailService(IHttpClientFactory factory)
    {
        _client = factory.CreateClient("Sendi");
    }

    public async Task<string> SendAsync(string from, string to, string subject, string html)
    {
        var payload = new { from, to = new[] { to }, subject, html };
        var response = await _client.PostAsJsonAsync("emails", payload);
        var result = await response.Content.ReadFromJsonAsync<JsonElement>();
        return result.GetProperty("id").GetString()!;
    }
}