How To Send Activation Link In Email After User Registration Details In MVC

Today, in this article, I will explain how to send an activation link on the email id after user registration using MVC and Web API. In real time, often, we see that after registration by the user, it will send a code to the registered email id and when we click this link, then it will activate our email id. Actually, what happens behind this is when we register our details, the system will send an activation code on email id and also saves the same link or code in our database and when we activate our email id, then it will check and match that with our database entry. If matched, it will activate the profile, otherwise it doesn't.

So now, let us see the required steps. I will explain in the next article how to successfully activate the email Id.

Step 1

We need to create two tables - one for RegistrationDetails and a second for Department.

MVC

MVC

 

Step2

Now, we need to create an MVC application but we will create two projects here - First for Web API project for the creation of service and the second is MVC project for consuming that service. So now, let us add the first MVC project.

Open Visual Studio and go to File->New ->Web application ->select MVC ->OK.

MVC

 

Step 3

Now, add tables in Web API project using Entity Framework. For this, go to Models folder ->right-click -> Add -> New item -> ADO.NET Entity Data Model -> click Add -> select database first approach->click Next.

Select "New Connection" and give the connection details, then select database -> click OK.

Choose tables and click OK.

MVC

 

Step 4

Now, we will write the logic for binding the department so, I create a folder, Business Logic, and take a class RegLogic.cs to write the logic for binding.

But before that, we add a folder in the Models folder. l will create a partial class of RegDetail.cs and add some properties for finding the address of local URL.

  1. namespace EmailActivationAPI.Models    
  2. {    
  3.     public partial class RegDetail    
  4.     {    
  5.         public string scheme { getset; }    
  6.         public string host { getset; }    
  7.         public string port { getset; }    
  8.     }    
  9. } 

After that, we will write the logic.

  1. public List<Department> BindDept()  
  2. {  
  3.     EmployeeDBEntities objEntity = new EmployeeDBEntities();  
  4.     return objEntity.Departments.ToList();  
  5. }  

Again, we will write logic for inserting the user details in RegLogic.cs class.

  1. public string RegisterUser(RegDetail objReg)  
  2. {  
  3.     objReg.EmailIVeryFied = false;  
  4.     objReg.ActivateionCode = Guid.NewGuid();  
  5.     EmployeeDBEntities objEntity = new EmployeeDBEntities();  
  6.     objEntity.RegDetails.Add(objReg);  
  7.     int i = objEntity.SaveChanges();  
  8.   
  9.     if(i > 0)  
  10.     {  
  11.         SendVerificationLinkEmail(objReg.EmailId, objReg.ActivateionCode.ToString(), objReg.scheme, objReg.host, objReg.port);  
  12.         return "Registration has been done,And Account activation link" + "has been sent your eamil id:" + objReg.EmailId;  
  13.     }  
  14.     else  
  15.     {  
  16.         return "Registration has been Faild";  
  17.   
  18.     }  
  19. }  

After that, we will write code for sending the activation code on email id.

  1. private void SendVerificationLinkEmail(string emailId, string activationcode, string scheme, string host, string port)  
  2. {  
  3.     var varifyUrl = scheme + "://" + host + ":" + port + "/JobSeeker/ActivateAccount/" + activationcode;  
  4.     var fromMail = new MailAddress("your email id""welcome mithilesh");  
  5.     var toMail = new MailAddress(emailId);  
  6.     var frontEmailPassowrd = "your password";  
  7.     string subject = "Your account is successfull created";  
  8.     string body = "<br/><br/>We are excited to tell you that your account is" +  
  9.       " successfully created. Please click on the below link to verify your account" +  
  10.       " <br/><br/><a href='" + varifyUrl + "'>" + varifyUrl + "</a> ";  
  11.   
  12.     var smtp = new SmtpClient  
  13.     {  
  14.         Host = "smtp.gmail.com",  
  15.         Port = 587,  
  16.         EnableSsl = true,  
  17.         DeliveryMethod = SmtpDeliveryMethod.Network,  
  18.         UseDefaultCredentials = false,  
  19.         Credentials = new NetworkCredential(fromMail.Address, frontEmailPassowrd)  
  20.   
  21.     };  
  22.     using (var message = new MailMessage(fromMail, toMail)  
  23.     {  
  24.         Subject = subject,  
  25.         Body = body,  
  26.         IsBodyHtml = true  
  27.     })  
  28.     smtp.Send(message);  
  29. }   

Step5

After that, we will add an API Controller in Web API project.

MVC

Now, we can see the our Web API project architecture.

MVC

Now, we have to write the WebAPI code.

  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Net;    
  5. using System.Net.Http;    
  6. using System.Web.Http;    
  7. using EmailActivationAPI.Models;    
  8. using EmailActivationAPI.BusinessLogic;    
  9.     
  10. namespace EmailActivationAPI.Controllers    
  11. {    
  12.     [RoutePrefix("api/UserReg")]    
  13.     public class RegAPIController : ApiController    
  14.     {    
  15.         RegLogic objReg = new RegLogic();    
  16.     
  17.         [HttpPost]    
  18.         [Route("RegUser")]    
  19.         public string RegisterUser(RegDetail data)    
  20.         {    
  21.             string strObj;    
  22.             try    
  23.             {    
  24.                 strObj = objReg.RegisterUser(data);    
  25.             }    
  26.             catch (ApplicationException ex)    
  27.             {    
  28.                 throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = ex.Message });    
  29.             }    
  30.             catch (Exception ex)    
  31.             {    
  32.                 throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadGateway, ReasonPhrase = ex.Message });    
  33.             }    
  34.     
  35.             return strObj;    
  36.         }    
  37.         [HttpGet]    
  38.         [Route("BindDepartment")]    
  39.         public List<Department> DeptBind()    
  40.         {    
  41.             List<Department> objDept = new List<Department>();    
  42.             try    
  43.             {    
  44.                 objDept = objReg.BindDept();    
  45.             }    
  46.             catch (ApplicationException ex)    
  47.             {    
  48.                 throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = ex.Message });    
  49.             }    
  50.             catch (Exception ex)    
  51.             {    
  52.                 throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadGateway, ReasonPhrase = ex.Message });    
  53.             }    
  54.     
  55.             return objDept;    
  56.         }    
  57.     }    
  58. } 

Step 5

Now, let's go in MVC project and add a Controller.

MVC

This is our MVC project architecture.

MVC

 

After that, create an action method and right click and add View and View page.

  1. public async Task<ActionResult> RegisterDetails()  
  2. {  
  3.     await DepartmentData();  
  4.     return View();  
  5. }  

Now, we have to add Model class. So here, I added two classes, first Department.cs  and second Register.cs

Department.cs  

  1. public class Department  
  2. {  
  3.     public int DeptId { get; set; }  
  4.     public string DeptName { get; set; }  
  5.     public string Location { get; set; }  
  6. }  

Register.cs

  1. public class Register  
  2. {  
  3.      public string FirstName { get; set; }  
  4.      public string LastName { get; set; }  
  5.      public string UserName { get; set; }  
  6.      public string EmailId { get; set; }  
  7.      public string Password { get; set; }  
  8.      public string MobileNo { get; set; }  
  9.      public string PineCode { get; set; }  
  10.      public string Address { get; set; }  
  11.      public int DeptID { get; set; }  
  12.      public string scheme { get; set; }  
  13.      public string host { get; set; }  
  14.      public string port { get; set; }  
  15. }  

Here, we will add a separate class for writing the logic for consuming the api service. So right click on the Models folder and add a class RestClient.cs and write logic

  1. public class RestClient    
  2. {     
  3.     private HttpClient client;    
  4.     public const string ApiUri = "http://localhost:49619/";    
  5.     public const string MediaTypeJson = "application/json";    
  6.     public const string RequestMsg = "Request has not been processed";    
  7.     public static string ReasonPhrase { getset; }    
  8.     public RestClient()    
  9.     {    
  10.         this.client = new HttpClient();    
  11.         this.client.BaseAddress = new Uri(ApiUri);    
  12.         this.client.DefaultRequestHeaders.Accept.Clear();    
  13.         this.client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypeJson));    
  14.     }    
  15.     public async Task<List<U>> RunAsyncGetAll<T, U>(dynamic uri)    
  16.     {    
  17.         HttpResponseMessage response = await this.client.GetAsync(uri);    
  18.         if (response.IsSuccessStatusCode)    
  19.         {    
  20.             return await response.Content.ReadAsAsync<List<U>>();    
  21.         }    
  22.         else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)    
  23.         {    
  24.             throw new ApplicationException(response.ReasonPhrase);    
  25.         }    
  26.         else if (response.StatusCode == System.Net.HttpStatusCode.BadGateway)    
  27.         {    
  28.             throw new Exception(response.ReasonPhrase);    
  29.         }    
  30.     
  31.         throw new Exception(RequestMsg);    
  32.     }    
  33.     
  34.     public async Task<U> RunAsyncPost<T, U>(string uri, T entity)    
  35.     {    
  36.         HttpResponseMessage response = client.PostAsJsonAsync(uri, entity).Result;    
  37.         ReasonPhrase = response.ReasonPhrase;    
  38.         if (response.IsSuccessStatusCode)    
  39.         {    
  40.             return await response.Content.ReadAsAsync<U>();    
  41.         }    
  42.         else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)    
  43.         {    
  44.             throw new ApplicationException(response.ReasonPhrase);    
  45.         }    
  46.         else if (response.StatusCode == System.Net.HttpStatusCode.BadGateway)    
  47.         {    
  48.             throw new Exception(response.ReasonPhrase);    
  49.         }    
  50.     
  51.         throw new Exception(RequestMsg);    
  52.     }   
  53. } 

Now we will write two methods, the first for binding department and the second for inserting the user details

  1. private RestClient restClient = new RestClient();  
  2. public async Task DepartmentData()  
  3. {  
  4.     var value = await this.restClient.RunAsyncGetAll<Department, Department>("api/UserReg/BindDepartment");  
  5.   
  6.     List<Department> lstDept = new List<Department>();  
  7.   
  8.     ViewBag.DeptDetails = new SelectList(value, "DeptId""DeptName");          
  9. }  
  10. [HttpPost]  
  11. public async Task<ActionResult> RegisterDetails(Register objReg)  
  12. {  
  13.     await DepartmentData();  
  14.            
  15.     objReg.scheme = Request.Url.Scheme;  
  16.     objReg.host = Request.Url.Host;  
  17.     objReg.port = Request.Url.Port.ToString();  
  18.     var value = await this.restClient.RunAsyncPost<Register, string>("api/UserReg/RegUser", objReg);  
  19.     TempData["Message"] = value;  
  20.     return RedirectToAction("SendLink");  
  21. }  

At last, we will create an action method in RegsterUser Controller

  1. public ActionResult SendLink()  
  2. {  
  3.     ViewBag.Message = TempData["Message"].ToString();  
  4.     return View();  
  5. }  

Let us run the project. We have to run both projects at the same time so we have to set some changes.

Right-click on the solution project and go to properties. There, check the "Multiple startup projects" option and click "Apply".

MVC

Now, finally, run the project and insert the user details.

MVC

 

When clicking the create button it displays the user-friendly message.

MVC

After this, we will check the user email id.

MVC

And also, we will check our database.

MVC

Conclusion

In this article, I explained how to send an activation link on email id after the registration of the user details. In the next article, I will explain how to activate the activation code after sending the link on email id.