How to send email using Mailgun API in C#

Mailgun is one of the best email service provider. Mailgun provides various ways to send email using their services. In this article, we will learn how to send email using Mailgun API in C# (CSharp).

Project Setup to send email using Mailgun API in C#:

You can use the Mailgun API in any dotnet project. Here for the learning purpose we will be using a Console application in dot net core.

Once you have created the application, we need to install the following package.

Install-Package RestSharp.Authenticators

Click here to get the NuGet link to the package.

RestSharp.Authenticators

Add data class:

To send the email using Mailgun API, we need to set couple of properties like Subject, To, Body etc.

Lets create a new UserEmailOptions class with these properties.

using System.Collections.Generic;

namespace EmailConsoleApp
{
    class UserEmailOptions
    {
        public List<string> ToEmails { get; set; }
        public string Subject { get; set; }
        public string Body { get; set; }
    }
}

Feel free to add more properties in this class based on your need.

Dependency Injection in Asp.Net Core (Singleton vs Transient vs Scoped)

Emailer class setup:

We need something that will contain the actual code to send the email.

Let’s add a new class EmailService in the project.

Assume this class as a service in your application. In case you are using DI (Dependency Injection) in your app, you need to register this class in the DI container.

You can also create the Interface for this class for a better clean code.

Required things from Mailgun:

To send email using Mailgun API in C#, we need following data from Mailgun

  • API key
  • Base URI
  • Domain (Make sure it is verified on Mailgun portal)
  • Sender address
  • Sender display name
  • Tag (Optional)

In our demo console application we will use hard coded data for all above properties. In real application you should read this data from a config file (appsettings.json in case of asp.net core)

Emailer Code:

Here is the code of our EmailService class –

using RestSharp;
using RestSharp.Authenticators;
using System;

namespace EmailConsoleApp
{
    static class EmailService
    {

        private const string APIKey = "xxxxxxxxxxxxxxx-xxxxx-xxxxx";
        private const string BaseUri = "https://api.mailgun.net/v3";
        private const string Domain = "xxxxxx.xxx";
        private const string SenderAddress = "sender@xxxxxxxx.xxx";
        private const string SenderDisplayName = "Sender Name";
        private const string Tag = "sampleTag";

        public static IRestResponse SendEmail(UserEmailOptions userEmailOptions)
        {

            RestClient client = new RestClient
            {
                BaseUrl = new Uri(BaseUri),
                Authenticator = new HttpBasicAuthenticator("api", APIKey)
            };

            RestRequest request = new RestRequest();
            request.AddParameter("domain", Domain, ParameterType.UrlSegment);
            request.Resource = "{domain}/messages";
            request.AddParameter("from", $"{SenderDisplayName} <{SenderAddress}>");

            foreach (var toEmail in userEmailOptions.ToEmails)
            {
                request.AddParameter("to", toEmail);
            }

            request.AddParameter("subject", userEmailOptions.Subject);
            request.AddParameter("html", userEmailOptions.Body);
            request.AddParameter("o:tag", Tag);
            request.Method = Method.POST;
            return client.Execute(request);
        }

    }
}

Few important points –

  • Make sure you are getting all the values from application config file.
  • Tag is completely optional.
  • Mailgun also provides the async version for Execute method. The name of the method is ExecuteAsync
  • The use of static class is optional. You can have a non static class and use the instance in other class or register it in the DI container and get the instance from DI provider.

Call the Emailer from Program class:

The EmailService class is ready. Now we need to use this class in the Program class to send the actual email.

using System;
using System.Collections.Generic;

namespace EmailConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            UserEmailOptions userEmailOptions = new UserEmailOptions()
            {
                Body = "This is sample body",
                Subject = "This is sample test",
                ToEmails = new List<string>() { "nitish.webgentle@gmail.com" }
            };

            var result = EmailService.SendEmail(userEmailOptions);

            Console.WriteLine(result.Content);
            Console.WriteLine("Email Sent");
        }
    }
}

Feel free to modify the class, properties, methods name etc as per your style.