C# / .NETSecurityDevOps
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

Enumeration Attacks
Protect Against Enumeration Attacks in 2022
July 15, 2022
1 min
Clouflare Worker Reverse Proxy
Misc
Reverse Proxy Cloudflare Worker
June 03, 2021
1 min
© 2022, All Rights Reserved.

Quick Links

Get In TouchAbout Me

Social Media