Email Notification Using Web API 2 in ASP.NET MVC 5

Introduction

In this article we will create the Web API and access the Web API using MVC 5 and send email using Web API 2.

Let’s start step by step:

  • Create ASP.NET Web API Application/ Project
  • Working with Web API Application
  • Adding a model
  • Adding a controller
  • Adding Helper class
  • Calling the Web Api with JavaScript and J Query (test web API)
  • Use Rest client to call the API and send Email Notification (Install Fiddler)

Create the project

Start Visual Studio 2013/2015 and from the File menu, select New, then Project.

Select the ASP.NET Web Application project template. Name the project Email Notification and click OK.

ASP.NET Web Application

Select a template Web API.

Web API

Add a model class

A model is an object that represents the data in your application. In this case, the only model is a TeamA item.

Add a model class

Add a class file “TeamA.cs”.

class

Replace the generated code with:

  1. namespace EmailNotification.Models  
  2. {  
  3.     public class TeamA  
  4.     {  
  5.         public int Id  
  6.         {  
  7.             get;  
  8.             set;  
  9.         }  
  10.         public string Name  
  11.         {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         public string Type  
  16.         {  
  17.             get;  
  18.             set;  
  19.         }  
  20.         public decimal Price  
  21.         {  
  22.             get;  
  23.             set;  
  24.         }  
  25.     }  
  26. }  
Add a controller

Add a controller

In the Add Scaffold wizard, select the Web API 2 Empty Controller: Name it EmailNotifier.

Web API 2

In the Add Controller dialog, name the controller "EmailNotifierController " and click Add.

Replace code with the following controller.
  1. public class EmailNotifierController: ApiController  
  2. {  
  3.     TeamGroupA[] teamA = new TeamGroupA[]  
  4.     {  
  5.         new TeamGroupA  
  6.         {  
  7.             Id = 1, Name = "zing", Type = "Cricket", Price = 1  
  8.         },  
  9.         new TeamGroupA  
  10.         {  
  11.             Id = 2, Name = "Yo-yo", Type = "Football", Price = 3.75 M  
  12.         },  
  13.         new TeamGroupA  
  14.         {  
  15.             Id = 3, Name = "soft", Type = "Software", Price = 16.99 M  
  16.         }  
  17.     };  
  18.     // Run the application  
  19.     public IEnumerable < TeamGroupA > GetAllTeams()  
  20.     {  
  21.         return teamA;  
  22.     }  
  23. }  
To keep the example simple, TeamGroupA has stored in a fixed array inside the controller class. But, in a real application, you would get it from the Data access layer or use some other external data source.

The controller defines two methods that return products:
  • The GetAllTeams method returns the entire list of products as an IEnumerable<TeamGroupA> type.

As we are working with Web API it may contain one or more methods.

Now add new model for AdpaterResponsebase for another API method as SendEmailNotification.cs.

AdapterResponseBase.cs

AdapterResponseBase.cs

Replace model code with the following code:

  1. using System;  
  2. using System.Collections.Generic;  
  3. namespace EmailNotification.Models  
  4. {  
  5.     public class ResponseBase  
  6.     {}  
  7.     public class RequestBase  
  8.     {}  
  9.     public class RequestBase < T > : RequestBase  
  10.     {  
  11.         public RequestBase()  
  12.         {}  
  13.         public RequestBase(T data)  
  14.         {  
  15.             Data = data;  
  16.         }  
  17.         public T Data  
  18.         {  
  19.             get;  
  20.             set;  
  21.         }  
  22.     }  
  23. }  
Add new Helper class file EMailHelper.cs to folder named Helpers.

new Helper class

Replace class code with the following:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. namespace Common.Helpers  
  7. {  
  8.     public class EMailHelper  
  9.     {  
  10.         // Note: To send email you need to add actual email id and credential so that it will work as expected  
  11.         public static readonly string EMAIL_SENDER = "[email protected]"// change it to actual sender email id or get it from UI input  
  12.         public static readonly string EMAIL_CREDENTIALS = "*******"// Provide credentials   
  13.         public static readonly string SMTP_CLIENT = "smtp-mail.outlook.com"// as we are using outlook so we have provided smtp-mail.outlook.com   
  14.         public static readonly string EMAIL_BODY = "Reset your Password <a href='http://{0}.safetychain.com/api/Account/forgotPassword?{1}'>Here.</a>";  
  15.         private string senderAddress;  
  16.         private string clientAddress;  
  17.         private string netPassword;  
  18.         public EMailHelper(string sender, string Password, string client)  
  19.         {  
  20.             senderAddress = sender;  
  21.             netPassword = Password;  
  22.             clientAddress = client;  
  23.         }  
  24.         public bool SendEMail(string recipient, string subject, string message)  
  25.         {  
  26.             bool isMessageSent = false;  
  27.             //Intialise Parameters  
  28.             System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient(clientAddress);  
  29.             client.Port = 587;  
  30.             client.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;  
  31.             client.UseDefaultCredentials = false;  
  32.             System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(senderAddress, netPassword);  
  33.             client.EnableSsl = true;  
  34.             client.Credentials = credentials;  
  35.             try  
  36.             {  
  37.                 var mail = new System.Net.Mail.MailMessage(senderAddress.Trim(), recipient.Trim());  
  38.                 mail.Subject = subject;  
  39.                 mail.Body = message;  
  40.                 mail.IsBodyHtml = true;  
  41.                 //System.Net.Mail.Attachment attachment;  
  42.                 //attachment = new Attachment(@"C:\Users\XXX\XXX\XXX.jpg");  
  43.                 //mail.Attachments.Add(attachment);  
  44.                 client.Send(mail);  
  45.                 isMessageSent = true;  
  46.             }  
  47.             catch(Exception ex)  
  48.             {  
  49.                 isMessageSent = false;  
  50.             }  
  51.             return isMessageSent;  
  52.         }  
  53.     }  
  54. }  
Add Model to pass input parameter to API method as EmailInput.cs.

Add Model
  1. using System;  
  2. namespace EmailNotofication.Models  
  3. {  
  4.     public class EmailInput  
  5.     {  
  6.         public string UserName  
  7.         {  
  8.             get;  
  9.             set;  
  10.         }  
  11.         public string EmailId  
  12.         {  
  13.             get;  
  14.             set;  
  15.         }  
  16.     }  
  17. }  
Now we will start with UI part.

Calling the Web API with Javascript and jQuery


Here we will add an HTML page that uses AJAX to call the web API. We'll use jQuery to make the AJAX calls and also to update the page with the results.

In Solution Explorer, right-click the project and select Add, then select New Item.

select New Item

In the Add New Item dialog, select the Web node under Visual C#, and then select the HTML Page item. Name the page "index.html".

Add html page

Replace everything in this file with the following:
  1. <!DOCTYPE html>  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3.   
  4. <head>  
  5.     <title>Notification App</title>  
  6. </head>  
  7.   
  8. <body>  
  9.     <div>  
  10.         <h2>All Teams</h2>  
  11.         <ul id="teams" /> </div>  
  12.     <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>  
  13.     <script>  
  14.         var uri = 'api/EmailNotifier/GetAllTeams';  
  15.         $(document).ready(function()  
  16.         {  
  17.             // Send an AJAX request  
  18.             $.getJSON(uri).done(function(data)  
  19.             {  
  20.                 // On success, 'data' contains a list of teams.  
  21.                 $.each(data, function(key, item)  
  22.                 {  
  23.                     // Add a list item for the teams.  
  24.                     $('<li>',  
  25.                     {  
  26.                         text: formatItem(item)  
  27.                     }).appendTo($('#teams'));  
  28.                 });  
  29.             });  
  30.         });  
  31.   
  32.         function formatItem(item)  
  33.         {  
  34.             return item.Name + ': $' + item.Price;  
  35.         }  
  36.     </script>  
  37. </body>  
  38.   
  39. </html>  
Getting a List of Teams

To get a list of teams, send an HTTP GET request to "/api/GetAllTeams".

Set index.html as start page:

HTML Page

Run the project,

Yippee! Here we got success for calling Web API using Ajax. Now let’s add method for Email Notification.

run

We will call SendEmailNotification API using RestClient.

Add the following method to controller:
  1. [HttpPost]  
  2. public async Task < IHttpActionResult > SendEmailNotification(EmailInput data)  
  3. {  
  4.     ResponseBase updateResponse = new ResponseBase();  
  5.     var updateRequest = new RequestBase < EmailInput > (data);  
  6.     try  
  7.     {  
  8.         EMailHelper mailHelper = new EMailHelper(EMailHelper.EMAIL_SENDER, EMailHelper.EMAIL_CREDENTIALS, EMailHelper.SMTP_CLIENT);  
  9.         var emailBody = String.Format(EMailHelper.EMAIL_BODY);  
  10.         if(mailHelper.SendEMail(data.EmailId, EMailHelper.EMAIL_SUBJECT, emailBody))  
  11.         {  
  12.             //   
  13.         }  
  14.     }  
  15.     catch(Exception ex)  
  16.     {}  
  17.     return Ok(updateResponse);  
  18. }  
email Notification

You need to add extension for RestClient to your chrome browser to call API.

Pass the parameter and do necessary changes to call API from rest client as in the following:

Pass the parameter

http://localhost:21084/api/EmailNotifier/SendEmailNotification

HTTPPOST
  1. Content-Type: application/json  
  2. {  
  3.    "UserName""xyz",  
  4.    "EmailId" : "[email protected]",  
  5. }  
Once you click on send button, you can verify input parameter by adding debug point to API in controller

verify input parameter

After successful execution we will get response as follows:
response

Note: To send email you need to add actual email id and credential so that it will work as expected.

Read more articles on ASP.NET:


Similar Articles