< 1 min read

Sending email in C# via the Mailgun API is about 3x faster than via SMTP.

They make it very straightforward, just requiring a form-encoded POST with basic authentication.

using (var httpClient = new HttpClient())
{
var authToken = Encoding.ASCII.GetBytes($"api:{_emailSettings.Value.ApiKey}");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authToken));
var formContent = new FormUrlEncodedContent(new Dictionary<string, string> {
{ "from", $"{_emailSettings.Value.DisplayName} <{_emailSettings.Value.From}>" },
{ "h:Reply-To", $"{_emailSettings.Value.DisplayName} <{_emailSettings.Value.ReplyTo}>" },
{ "to", email },
{ "subject", subject },
{ "text", txtMessage },
{ "html", htmlMessage }
});
var result = await httpClient.PostAsync($"https://api.mailgun.net/v3/{_emailSettings.Value.EmailDomain}/messages", formContent);
result.EnsureSuccessStatusCode();
}
view raw mailgun.cs hosted with ❤ by GitHub

Full API reference can be found here: https://documentation.mailgun.com/en/latest/api-sending.html#sending

Was this post helpful?