Identity Email Service with Mailgun

03 Nov 2017   No Comments   970 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.

<system.net>
    <mailSettings>
        <smtp deliveryMethod="Network" from="yourname@gmail.com">
            <network host="smtp.gmail.com" port="587" userName="yourname@gmail.com" password="your_password" enableSsl="true" />
        </smtp>
    </mailSettings>
</system.net>

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 = "sandboxe3121b4943524cfc9fc7f071a47e90a5.mailgun.org";
        byte[] apiKeyAuth = Encoding.ASCII.GetBytes($"api:{apiKey}");
        
        var httpClient = new HttpClient { BaseAddress = new Uri("https://api.mailgun.net/v3/") };
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(apiKeyAuth));

        var form = new Dictionary<string, string>
        {
            ["from"] = "postmaster@sandboxe3121b4943524cfc9fc7f071a47e90a5.mailgun.org",
            ["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!