Thursday, 13 February 2014

Send user Confirmation email after Registration with Activation Link in ASP.Net

In this article I will explain how to send user confirmation email after registration with Activation link in ASP.Net using C# and VB.Net.
In order to validate the email address of the user provided during registration, a confirmation email with activation link in sent to the email address and when user clicks the link, his email address is verified and his account gets activated.
Database
In the previous article we have already created database named LoginDB which contains the following table named Users in it. For this article I have created a new table named UserActivation.
On the registration page I have made some changes in the RegisterUser event handler, if the username and email address are found valid then the SendActivationEmail method is executed
C#
protected void RegisterUser(object sender, EventArgs e)
{
    int userId = 0;
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("Insert_User"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@Username", txtUsername.Text.Trim());
                cmd.Parameters.AddWithValue("@Password", txtPassword.Text.Trim());
                cmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim());
                cmd.Connection = con;
                con.Open();
                userId = Convert.ToInt32(cmd.ExecuteScalar());
                con.Close();
            }
        }
        string message = string.Empty;
        switch (userId)
        {
            case -1:
                message = "Username already exists.\\nPlease choose a different username.";
                break;
            case -2:
                message = "Supplied email address has already been used.";
                break;
            default:
                message = "Registration successful. Activation email has been sent.";
                SendActivationEmail(userId);
                break;
        }
        ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + message + "');", true);
    }
}
Inside the SendActivationEmail method, a unique Activation code is generated using Guid’s NewGuid method and it is inserted in the UserActivation table.
Then an email is sent to the user’s email address with the URL of the Activation page with generated Activation Code in the QueryString of the URL
C#
private void SendActivationEmail(int userId)
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    string activationCode = Guid.NewGuid().ToString();
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand("INSERT INTO UserActivation VALUES(@UserId, @ActivationCode)"))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.AddWithValue("@UserId", userId);
                cmd.Parameters.AddWithValue("@ActivationCode", activationCode);
                cmd.Connection = con;
                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }
        }
    }
    using (MailMessage mm = new MailMessage("sender@gmail.com", txtEmail.Text))
    {
        mm.Subject = "Account Activation";
        string body = "Hello " + txtUsername.Text.Trim() + ",";
        body += "<br /><br />Please click the following link to activate your account";
        body += "<br /><a href = '" + Request.Url.AbsoluteUri.Replace("CS.aspx", "CS_Activation.aspx?ActivationCode=" + activationCode) + "'>Click here to activate your account.</a>";
        body += "<br /><br />Thanks";
        mm.Body = body;
        mm.IsBodyHtml = true;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.EnableSsl = true;
        NetworkCredential NetworkCred = new NetworkCredential("sender@gmail.com", "<password>");
        smtp.UseDefaultCredentials = true;
        smtp.Credentials = NetworkCred;
        smtp.Port = 587;
        smtp.Send(mm);
    }
}
 
 Activation email sent to the user
 
 
 
 
 

No comments:

Post a Comment