Emails using Mailgun in ASP.NET Core

Updated version of this post can be found here.

At last month’s Nashville .Net Users Group meeting Michael McCann when over some of the aspects of ASP.NET’s membership provider (non-core version). One of the things he talked about was enabling email as part of the user sign up process and for use in password recovery. This post is going to cover the same emailing aspect but in ASP.NET core using mailgun to actually send emails.

Account Controller

In the account controller most of the code needed is already present and just needs to be uncommented. In the Register function uncomment the following which will send the user an email asking that the address be confirmed. This of course stops users from signing up with email addresses they don’t actually have access to.

var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
var callbackUrl = Url.Action("ConfirmEmail", 
                             new { userId = user.Id, code = code }, 
                             protocol: HttpContext.Request.Scheme);
await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
  "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>");

And then comment out this next line which would sign the user in before they have used the email above to confirm their account.

//await _signInManager.SignInAsync(user, isPersistent: false);

Next in the Login function add the following bit of code just before the call to _signInManager.PasswordSignInAsync. This looks up the user by email address and returns an error if the account has not been confirmed.

var user = await _userManager.FindByNameAsync(model.Email);
if (user != null)
    if (!await _userManager.IsEmailConfirmedAsync(user))
                                 "You must have a confirmed email to log in.");
        return View(model);

The last change is in the ForgotPassword function. Uncomment the following code to send the user an email to reset their password.

var code = await _userManager.GeneratePasswordResetTokenAsync(user);
var callbackUrl = Url.Action("ResetPassword", 
                             new { userId = user.Id, code = code }, 
                             protocol: HttpContext.Request.Scheme);
await _emailSender.SendEmailAsync(model.Email, "Reset Password",
 "Please reset your password by clicking here: <a href=\"" + callbackUrl + "\">link</a>");
return View("ForgotPasswordConfirmation");

Forgot Password View

In ForgotPassword.cshtml uncomment the following section to show the UI associated with email based password reset.

<form asp-controller="Account" asp-action="ForgotPassword" method="post" class="form-horizontal" role="form">
    <h4>Enter your email.</h4>
    <hr />
    <div asp-validation-summary="ValidationSummary.All" class="text-danger"></div>
    <div class="form-group">
        <label asp-for="Email" class="col-md-2 control-label"></label>
        <div class="col-md-10">
            <input asp-for="Email" class="form-control" />
            <span asp-validation-for="Email" class="text-danger"></span>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <button type="submit" class="btn btn-default">Submit</button>

Caution for existing sites

With the changes above if a user has not confirmed their email address then they will not be able to log in or reset their password. Any existing users would need to have their accounts marked as confirmed manually by updating the EmailConfirmed bit field in the AspNetUsers table or be provided away to confirm their account.


Mailgun is an email service that provides a simple API for sending emails and allows up to 10,000 emails to be sent free every month. I have only used mailgun for sending test emails so I can’t speak to how it holds up at scale.

After signing up for an account click on the domains tab and select the only existing active domain which should start with something like sandbox.

Storing Configuration

In my project I created an EmailSettings class that will be loaded from user secrets in the start up of the application. For more details on general configuration in ASP.NET Core check out this post and thenthis post for more details on user secrets. The following is my email settings class.

public class EmailSettings
    public string ApiKey { get; set; }
    public string BaseUri { get; set; }
    public string RequestUri { get; set; }
    public string From { get; set; }

If using mailgun the above fields map to the following from the mailgun domain page.

EmailSettings Mailgun Example
ApiKey API Key key-*
BaseUri API Base URL
RequestUri API Base URL sandbox*
From Default SMTP Login [email protected]*

A couple of notes to the above table on what I actually saved in my config files.

EmailSettings Field Note Example
ApiKey Used with basic auth and needs username api:key-*
RequestUri Needs the API end point to call sandbox*

The following is what my actual config files ends up looking like.

  "EmailSettings": {
    "ApiKey": "api:key-*",
    "BaseUri": "",
    "RequestUri": "sandbox*",
    "From": "[email protected]*"

In the ConfigureServices function Startup.cs I added a reference to the new settings class so it would be available for dependency injection.


Message Services

In the Services folder there is a MessageServices.cs file which contains the AuthMessageSender class that has an empty implementation for sending email base on an IEmailSender interface which defines a single SendEmailAsync method. This function is already being called in the code that was uncommented above so I am going to use it to call mailgun’s API.

First I need to get the email settings defined above injected into the AuthMessageSenderClass by adding a class level field and a constructor. The only thing the constructor is doing is saving a reference to the injected settings class.

private readonly EmailSettings _emailSettings;

public AuthMessageSender(IOptions<EmailSettings> emailSettings)
    _emailSettings = emailSettings.Value;

Next is the SendEmailAsync function mentioned above which I changed to an async function and added the code to send an email using mailgun’s API.

public async Task SendEmailAsync(string email, string subject, string message)
    using (var client = new HttpClient { BaseAddress = new Uri(_emailSettings.BaseUri) })
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",

        var content = new FormUrlEncodedContent(new[]
            new KeyValuePair<string, string>("from", _emailSettings.From),
            new KeyValuePair<string, string>("to", email),
            new KeyValuePair<string, string>("subject", subject),
            new KeyValuePair<string, string>("text", message)

        await client.PostAsync(_emailSettings.RequestUri, content).ConfigureAwait(false);

This code is using the HttpClient to send a request to mailgun’s API using basic authorization and form url encoded content to pass the API the relevant bit of information.

With that your application will now email account conformations and password resets.

Other Email Options

Mailgun is obviously not the only option for sending emails. This post from Mashape lists 12 API providers. In addition SMTP is also an option which this post by Steve Gordon covers.

Basic Configuration with Aurelia

If you have been following my Aurelia posts using an ASP.NET 5 web API then you will have noticed that I have been hardcoding the API url. In this post I am going to cover the basics of configuration in Aurelia which will allow the API url to be in a single location instead of spread all over the application.

Configuration will be done using the Aurelia-Configuration plugin. To install open a console window and navigate to the folder that contains the application’s package.json file and run the following command.

jspm install aurelia-configuration

If you are using Visual Studio to find your package.json make sure to click the show all files button in the solution explorer. With the release of RC1 package.json is hidden by default.

First code change is in the html file that kicks off Aurelia. The changed part is on the first line with aurelia-app which changed to aurelia-app=”main”.

<div aurelia-app="main">
    <script src="../jspm_packages/system.js"></script>
    <script src="../config.js"></script>

Next add a main.js file in the wwwroot folder. This file will be called when Aurelia is bootstrapped and will control how Aurelia is bootstrapped. Everything in this file is the default Aurelia bootstrapping process other than “.plugin(‘aurelia-configuration’)” which is the part that needs to be added for configuration to work.

export function configure(aurelia) {

  aurelia.start().then(a => a.setRoot());

By default the configuration plugin looks for an application.json inside of a config directory in the root directory. This tripped me up a bit as I was expecting this to be a config directory inside of wwwroot, but that is not exactly the case. Root in the case means root for the Aurelia application context. In my case my Aurelia app is launched from a HomeController which means the application.json file needed to be in wwwroot/Home/config. Here is my application.json file with the base url for my test API.

	"api": {
		"baseUrl": "http://localhost:18907/api/"

Now to get access to the configuration information. First add an import for configuration.

import {Configure} from 'aurelia-configuration';

Add Configure to the inject decorator.

@inject(HttpClient, Router, EventAggregator, Configure)

And to the constructor.

constructor(http, router, eventAggregator, configAurelia)

Now the actual usage of a config value with a before and after for comparison.



Here is all of the above together for reference.

import {Configure} from 'aurelia-configuration';

@inject(HttpClient, Router, EventAggregator, Configure)
export class Detail{

    constructor(http, router, eventAggregator, configAurelia){
        http.configure(config => {

        this.http = http;
        this.router = router;
        this.eventAggregator = eventAggregator;

That is all there is for basic configuration with Aurelia. Check out the plugin’s site for examples of how set up configurations for different environments, setting the config directory as well as filename.

Configuration in ASP.NET 5

ASP.NET 5 offer a lot of options for loading configuration data such as json files, ini files, XML files, in memory collections, command line arguments, user secrets and environment variables.

The following has at least one example of each type of configuration. Configurations are setup in the constructor of the Startup class.

public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv)
    // Setup configuration sources.
    var builder = new ConfigurationBuilder(appEnv.ApplicationBasePath)
        .AddJsonFile($"config.{env.EnvironmentName}.json", optional: true)
        .AddIniFile("config.ini", optional: true)
        .AddInMemoryCollection(new Dictionary<string, string="">
        .AddXmlFile("config.xml", optional:true);

    if (env.IsDevelopment())
    Configuration = builder.Build();

As you can see from the example all the different configuration sources can be used together without any issues. A critical thing to keep in mind is if a configuration option is set in multiple places the last configuration source’s value will be used. For example, using the code above, if the title of a site was sent in config.json and config.ini then the value from config.ini would be used.

An example I have seen the ASP.NET team use many times is to use user secrets for API key when in development and then store the keys in environment variables for production.

Here are the relevant lines from the dependencies section of the project.json file.

"Microsoft.Framework.Configuration.Abstractions": "1.0.0-beta7",
"Microsoft.Framework.Configuration.Json": "1.0.0-beta7",
"Microsoft.Framework.Configuration.UserSecrets": "1.0.0-beta7",
"Microsoft.Framework.Configuration.Xml" : "1.0.0-beta7"

Another great feature is being able to load an object with the values from a configuration section. The following is a class created to hold the settings for an application.

public class AppSettings
    public string Title { get; set; }
    public string TagLine { get; set; }

Then in the ConfigureServices function this is all that is needed to load the class.


Now instead of directly accessing the configuration classes in the HomeController the AppSettings class can be used instead. Here is an example of using ASP.NET 5’s built-in dependency to automatically get a reference to AppSetting via constructor injection.

private readonly IOptions _appSettings;

public HomeController(IOptions appSettings)
    _appSettings = appSettings;

And then using the _appSettings in the index action to pass values to the view.

public IActionResult Index()
    ViewData["Title"] = $"{_appSettings.Options.Title} - " +
    return View();

The above is using C# 6’s new interpolated string feature.  The dollar sign before the string is what triggers the feature and allow use variables when wrapped in curly braces.

Check out this github repo for the internals of configuration in ASP.NET 5 .

I also recommend checking out the new Introduction to ASP.NET 5 course on Microsoft Virtual Academy. It covers a lot of good information including which is a production site used to for the ASP.NET 5 community stand up.