C# / .NETDevOpsMisc
C# / .NET
C# Sending Emails with the Mailgun API
Alexandru Puiu
Alexandru Puiu
December 01, 2020
1 min

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


Tags

securitycloudflare
Alexandru Puiu

Alexandru Puiu

Engineer / Security Architect

Systems Engineering advocate, Software Engineer, Security Architect / Researcher, SQL/NoSQL DBA, and Certified Scrum Master with a passion for Distributed Systems, AI and IoT..

Expertise

.NET
RavenDB
Kubernetes

Social Media

githubtwitterwebsite

Related Posts

Authentication in HttpClientFactory
Authentication in Http Client Factory
December 21, 2022
1 min

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!
© 2023, All Rights Reserved.

Quick Links

Get In TouchAbout Me

Social Media