Use HttpClient to call Maigun API in ASP.NET Core

I had to send some emails from an ASP.NET Core 2.2 web application. One option to send emails is to use Mailgun. To send email using Mailgun you need to create a free account. You cand send 10,000 email per month for free.


For sending SMTP or HTTP can be used. HTTP API has 2 main advantages over SMTP:

  • It’s faster
  • You don’t have to deal with MIME types

HTTP API using C#

So for sending emails, I chose to use the HTTP API. On the Mailgun website, there are examples for sending emails using C#. These examples are using the RestSharp library which is an excellent option but I didn’t want to use another library. I wanted to use HttpClientFactory and HttpClient to call the Mailgun HTTP API. HttpClientFactory already has great integration with DI and the rest of ASP.NET Core.

Sending emails

I created a class to retain the email config.
MailgunEmailSender class is responsible to send emails by calling the Mailgun HTTP API. It takes as parameters in the constructor the HttpClient that will be used to call the API and the email config. It has just one public method called SendMail. SendMail takes 3 parameters: to the email address, email subject, and email body. It calls the Mailgun API using HttpClient that is configured in Startup.cs. Please take a look below at the code:

In Startup.cs the email config is loaded and setup for MailgunEmailSender how to use HttpClient is made.

Github sample repository

All the sample code is available on github at

Share with:

3 thoughts to “Use HttpClient to call Maigun API in ASP.NET Core”

Leave a Reply

Your email address will not be published. Required fields are marked *