Identity Email Service with Mailgun

03 Nov 2017   No Comments   969 Views

If you've worked with ASP.NET Identity before you should be familiar with EmailService and SmsService classes. They're responsible for sending user notifications, like when a password is changed, or when a user requests to reset their password. There's no default implementation so you'll have to write your own services to actually use them. If you have access to a valid email account and its SMTP settings, you can configure <mailSettings> under Web.config and send your emails. You can see an example in the listing below.

        <smtp deliveryMethod="Network" from="">
            <network host="" port="587" userName="" password="your_password" enableSsl="true" />

Another option is to utilize an excellent platform such as Mailgun. which is pretty awesome and covers all your mailing needs. you can learn more from the official guide and docs. assuming you have signed up and have access to your API keys, you can write an email service like the listing below. nothing fancy here, we just create a new HttpClient and send a HTTP request to send our emails.

public class EmailService : IIdentityMessageService
    public Task SendAsync(IdentityMessage message)
        const string apiKey = "key-9927c9ba92d7871faa30a24398dc4db1";
        const string sandBox = "";
        byte[] apiKeyAuth = Encoding.ASCII.GetBytes($"api:{apiKey}");
        var httpClient = new HttpClient { BaseAddress = new Uri("") };
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(apiKeyAuth));

        var form = new Dictionary<string, string>
            ["from"] = "",
            ["to"] = message.Destination,
            ["subject"] = message.Subject,
            ["text"] = message.Body

        HttpResponseMessage response = httpClient.PostAsync(sandBox + "/messages", new FormUrlEncodedContent(form)).Result;

        return Task.FromResult((int)response.StatusCode);

Happy coding!