Confirming a user's email address with SendGrid

Let's be honest, having a user click a link in an email they received to confirm their email address is messy and a bit redundant if you think about it.
Using SendGrid to send emails provides you with an awesome amount of stats, so make use of it and create a better user experience.

The Problem

Users are lazy and tend not click a link to confirm their email address unless forced.

The Solution

After a user logins in, check if their email address is confirmed if not, use the code below in a background task to check their email activity on SendGrid.

The How

Nuget Packages

The first step is installing the SendGrid package into your project.
SendGrid

Also add a reference to.
System.Configuration


Config Setup

In your config file add this app setting.
key="SendGridApiKey" value="Your SendGrid API Key Here"


Putting It Together

First we need to call the SendGrid API to get the email activity for the user.

var email = "dev@lionelchetty.co.za";
var sendGridApiKey = ConfigurationManager.AppSettings["SendGridApiKey"];

var client = new SendGrid.SendGridClient(sendGridApiKey);
string queryParams = $"{{'limit':100,'email': '{email}'}}";
var response = await client.RequestAsync(method: SendGridClient.Method.GET, urlPath: "email_activity", queryParams: queryParams);

To deserialize the response json, you can use the following class.

public class SendGridQueryResponseModel
    {
        public DateTime timestamp
        {
            get { return new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(this.created); }                
        }
        public int created { get; set; }
        public string email { get; set; }
        public string @event { get; set; }
    }

Lastly we'll need to filter the list of activities for 'open' or 'delivered' and update the user accordingly.

if (response.StatusCode == System.Net.HttpStatusCode.OK)
        {
            var json = await response.Body.ReadAsStringAsync();
            if (!string.IsNullOrEmpty(json))
            {
                var emailActivity = JsonConvert.DeserializeObject<List<SendGridQueryResponseModel>>(json);
                if (emailActivity.FirstOrDefault(x => x.@event == "open") != null)
                {
                    var emailConfirmed = true;
                }
            }
        }

An example project is on GitHub.