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();
}

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


Subscribe To My Newsletter

I'll only send worthwhile content I think you'll want, less than once a month, and promise to never spam or sell your information!