Mailhive 0.3.0

dotnet add package Mailhive --version 0.3.0
                    
NuGet\Install-Package Mailhive -Version 0.3.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Mailhive" Version="0.3.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Mailhive" Version="0.3.0" />
                    
Directory.Packages.props
<PackageReference Include="Mailhive" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Mailhive --version 0.3.0
                    
#r "nuget: Mailhive, 0.3.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Mailhive@0.3.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Mailhive&version=0.3.0
                    
Install as a Cake Addin
#tool nuget:?package=Mailhive&version=0.3.0
                    
Install as a Cake Tool

Mailhive

The official .NET SDK for Mailhive Send. It targets .NET 8 and .NET Standard 2.0, so it also runs on .NET Framework 4.6.2 and later.

dotnet add package Mailhive

Send an email

using Mailhive;

using var client = new MailhiveClient(); // reads MAILHIVE_API_KEY

var email = await client.Emails.SendAsync(new SendEmailRequest
{
    From = "Acme <hello@acme.com>",
    To = "ada@example.com",
    Subject = "Your receipt",
    Html = "<p>Thanks for your order.</p>",
});
Console.WriteLine(email.Id);

The JSON names match the API reference exactly. SendEmailRequest also has Cc, Bcc, ReplyTo, Headers, Tags, TemplateId, Variables and Attachments. Properties you leave null aren't sent.

Recipients take one address or several:

To = "ada@example.com",
Cc = new[] { "grace@example.com", "Alan <alan@example.com>" },

Attachments take bytes, which are base64-encoded for you, or text that's already base64:

Attachments = new List<Attachment>
{
    new Attachment("receipt.pdf", pdfBytes, "application/pdf"),
    Attachment.FromBase64("logo.png", logoBase64, "image/png"),
    Attachment.FromFile("terms.txt"),
},

Templates

await client.Emails.SendAsync(new SendEmailRequest
{
    From = "hello@acme.com",
    To = "ada@example.com",
    TemplateId = "tpl_…",
    Variables = new Dictionary<string, object?> { ["name"] = "Ada", ["total"] = 42.5 },
});

Batch and look-up

IReadOnlyList<AcceptedEmail> accepted = await client.Emails.SendBatchAsync(new[] { email1, email2 }); // up to 100; all accepted or none
Email sent = await client.Emails.GetAsync(accepted[0].Id); // sent.Status: "delivered", "bounced", …

Every method takes a CancellationToken.

Check addresses before sending

var verdicts = await client.Emails.ValidateAsync(new[] { "ada@gmial.com" });
// verdicts[0].Valid == false, Reason "domain_typo", Suggestion "ada@gmail.com", Message "The domain looks mistyped."

The same checks run on every send: an address that can't work is left out and listed in the accepted email's Rejected (address → reason), so it never bounces.

Audiences and contacts

With an API key that has Full access, keep an audience in step with your app or CRM:

var contact = await client.Contacts.UpsertAsync(audienceId, new ContactInput
{
    Email = "ada@example.com",
    FirstName = "Ada",
    Fields = new Dictionary<string, string> { ["plan"] = "pro" },
});

UpsertAsync adds the person, or updates them if they're already there, so it's safe to repeat. Other calls: Audiences.ListAsync, CreateAsync, RenameAsync; Contacts.ListAsync (set Email in the options to find one person), AddAsync, UpsertBatchAsync (up to 100; check each result's Ok), GetAsync, UpdateAsync, UnsubscribeAsync and DeleteAsync.

Someone who unsubscribed, or reported your email as spam, can't be subscribed again by your code: you get a ConflictException with code contact_unsubscribed. To bring them back, ask them to confirm:

await client.Contacts.UpsertAsync(audienceId, new ContactInput
{
    Email = "ada@example.com",
    DoubleOptIn = new DoubleOptIn { From = "Acme News <news@yourcompany.com>", Subject = "Confirm your subscription" },
});

They're pending, and never mailed by a broadcast, until they click the link. See the contacts API reference.

Retries and idempotency

Every send carries an Idempotency-Key. Retries reuse it, so a retry never sends twice.

  • Retried (up to 2 times by default): network errors, timeouts, 5xx responses, and 429 rate_limited after the Retry-After delay. Otherwise the SDK backs off exponentially with jitter (about 0.5s, 1s, 2s, up to 8s).
  • Not retried: a used-up allowance (monthly_quota_reached, daily_cap_reached), invalid requests, and a Retry-After longer than 60 seconds.

To stay safe across restarts, pass your own key:

await client.Emails.SendAsync(email, new SendOptions { IdempotencyKey = $"order-{order.Id}-receipt" });

Errors

try
{
    await client.Emails.SendAsync(email);
}
catch (ValidationException error)
{
    Console.WriteLine($"{error.Code}: {error.Message} {error.Details} ({error.RequestId})");
}
catch (RateLimitException error) when (error.Code == "monthly_quota_reached")
{
    // Upgrade, or wait for next month.
}
Exception Status
AuthenticationException 401
BillingException 402
PermissionException 403
NotFoundException 404
ConflictException 409 (e.g. idempotency_conflict)
ValidationException 400, 422
RateLimitException 429 (RetryAfter)
MailhiveApiException other statuses, and the base class of all of the above
MailhiveConnectionException no response

API errors carry StatusCode, Code (stable: check this, not the message), Message, Details (a JsonElement?), RequestId (quote it to support) and Headers. Every exception the SDK throws is a MailhiveException.

Webhooks

Pass the raw body, exactly as received. Parsing and re-serializing it changes the bytes, so the signature can't match.

// ASP.NET Core minimal API
app.MapPost("/webhooks/mailhive", async (HttpRequest request, IConfiguration config) =>
{
    var payload = await new StreamReader(request.Body).ReadToEndAsync();
    try
    {
        var evt = MailhiveWebhook.Verify(
            payload,
            request.Headers[MailhiveWebhook.SignatureHeader],
            config["Mailhive:WebhookSecret"]!);

        if (evt.Type == "email.bounced")
        {
            var address = evt.Data.GetProperty("recipient").GetString();
            // …
        }
        return Results.Ok();
    }
    catch (WebhookVerificationException)
    {
        return Results.BadRequest();
    }
});

Verify checks the HMAC-SHA256 signature in constant time, accepts several v1= values (so secrets can be rotated), and refuses timestamps more than 300 seconds from now (pass tolerance to change it). The event has Type, CreatedAt, Test, Data and Raw (both JsonElement). A failure's Reason is header, timestamp or signature.

Dependency injection

MailhiveClient is thread-safe: register one and reuse it.

builder.Services.AddSingleton(new MailhiveClient(new MailhiveOptions
{
    ApiKey = builder.Configuration["Mailhive:ApiKey"],
}));

// or bind every option from configuration ("Mailhive": { "ApiKey": "…", "Timeout": "00:00:10" })
builder.Services.AddSingleton(_ =>
    new MailhiveClient(builder.Configuration.GetSection("Mailhive").Get<MailhiveOptions>()));

Then take MailhiveClient in your constructors or endpoint parameters. To send through your own HttpClient (for example one with a proxy), pass it as the second argument. The client doesn't dispose an HttpClient you pass in.

Options

new MailhiveClient(new MailhiveOptions
{
    ApiKey = "mhs_…",                                 // default: MAILHIVE_API_KEY
    BaseUrl = "https://api-beta.mailhive.africa/v1",  // default: MAILHIVE_BASE_URL, then production
    Timeout = TimeSpan.FromSeconds(30),               // per attempt
    MaxRetries = 2,
});

The server SDK needs a secret key (mhs_…). It refuses a form's publishable key (mhp_…), and never includes the key in ToString().

Test keys (mhs_test_…) work unchanged: delivery is simulated and nothing is billed, and AcceptedEmail.Test is true. More about test keys.

Development

cd dotnet
dotnet test   # needs node on PATH: the conformance suite runs against mock-server/server.mjs
dotnet pack -c Release

Releases are tagged dotnet-v<version> from main; the tag must match <Version> in src/Mailhive/Mailhive.csproj.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.3.0 103 11/9/2026
0.2.0 116 10/26/2026
0.1.0 120 10/1/2026