Send Email Using ASP.NET MVC And Web API

Introduction

 
In this article, we will learn how to send emails using SMTP Server in ASP.NET MVC with Web API. There are many ways to send an email - SMTP, POP3, IMAP, Exchange Web Services, Outlook Interop, etc. Here, we will use SMTP (Gmail).
 
For sending an email via SMTP, the .NET framework includes a library System.Net.Mail namespace. Now, I will show how to do it step by step.
 
Step 1
 
Open Visual Studio and go to File » New » Project. Create a new project. Select Visual C# from templates and choose Web and give the project name as MailSendingWithWebApi and then click OK.
 
Send Email Using ASP.NET MVC And Web API
 
Step 2
 
Choose MVC from "Select a template" window and check Web API from "Add folders and core references for:" section and click OK.
 
Send Email Using ASP.NET MVC And Web API
 
Step 3
 
Now, create a new class in the Models folder and name it as EmailModel.cs.
 
Code for EmailModel.cs 
  1. using System.ComponentModel.DataAnnotations;  
  2.   
  3. namespace MailSendingWithWebApi.Models  
  4. {  
  5.     public class EmailModel  
  6.     {  
  7.         [Required, Display(Name = "Your name")]  
  8.         public string toname { getset; }  
  9.         [Required, Display(Name = "Your email"), EmailAddress]  
  10.         public string toemail { getset; }  
  11.         [Required]  
  12.         public string subject { getset; }  
  13.         [Required]  
  14.         public string message { getset; }  
  15.     }  
  16. }  
Step 4
 
Create a new Web API Controller in the Controllers folder and name it as EmailController. For that, right-click on the Controllers folder and click on Add --> Controller --> Web API 2 Controller- Empty --> Add.
 
Send Email Using ASP.NET MVC And Web API
 
Send Email Using ASP.NET MVC And Web API
Code for EmailController.cs
  1. using Newtonsoft.Json.Linq;  
  2. using System.IO;  
  3. using System.Net.Mail;  
  4. using System.Threading.Tasks;  
  5. using System.Web;  
  6. using System.Web.Http;  
  7.   
  8. namespace MailSendingWithWebApi.Controllers  
  9. {  
  10.     [RoutePrefix("api/email")]  
  11.     public class EmailController : ApiController  
  12.     {  
  13.         [HttpPost]  
  14.         [Route("send-email")]  
  15.         public async Task SendEmail([FromBody]JObject objData)  
  16.         {  
  17.             var message = new MailMessage();  
  18.             message.To.Add(new MailAddress(objData["toname"].ToString() + " <" + objData["toemail"].ToString() + ">"));  
  19.             message.From = new MailAddress("Amit Mohanty <[email protected]>");  
  20.             message.Bcc.Add(new MailAddress("Amit Mohanty <[email protected]>"));  
  21.             message.Subject = objData["subject"].ToString();  
  22.             message.Body = createEmailBody(objData["toname"].ToString(), objData["message"].ToString());  
  23.             message.IsBodyHtml = true;  
  24.             using (var smtp = new SmtpClient())  
  25.             {  
  26.                 await smtp.SendMailAsync(message);  
  27.                 await Task.FromResult(0);  
  28.             }  
  29.         }  
  30.   
  31.         private string createEmailBody(string userName, string message)  
  32.         {  
  33.             string body = string.Empty;  
  34.             using (StreamReader reader = new StreamReader(HttpContext.Current.Server.MapPath("/htmlTemplate.html")))  
  35.             {  
  36.                 body = reader.ReadToEnd();  
  37.             }  
  38.             body = body.Replace("{UserName}", userName);  
  39.             body = body.Replace("{message}", message);  
  40.             return body;  
  41.         }  
  42.     }  
  43. }  
Here, we use MailMessage Class to send mail. There are some minimum required properties of the MailMessage class that we have used here.
  • From - Sender’s email address.
  • To - Recipient(s) Email Address.
  • CC - Carbon Copies (Optional). Put the email address(s) here if you are sending a copy for their information and you want everyone to explicitly see this.
  • BCC - Blind Carbon Copies (Optional). Put the email address here if you are sending them a copy and you do not want the other recipients to see that you sent it to this contact.
  • Subject - Subject of the Email.
  • Body - Body of the Email.
  • IsBodyHtml - Specify whether body contains text or HTML mark up.
Step 5
 
Now, modify the Index.cshtml page with the below code.
 
Code for Index.cshtml 
  1. @model MailSendingWithWebApi.Models.EmailModel  
  2. @{  
  3.     ViewBag.Title = "Test Email";  
  4. }  
  5.   
  6. @using (Html.BeginForm())  
  7. {  
  8.     @Html.AntiForgeryToken()  
  9.     <h4>Send your message.</h4>  
  10.     <hr />  
  11.     <div class="form-group">  
  12.         @Html.LabelFor(m => m.toname, new { @class = "col-md-2 control-label" })  
  13.         <div class="col-md-10">  
  14.             @Html.TextBoxFor(m => m.toname, new { @class = "form-control" })  
  15.             @Html.ValidationMessageFor(m => m.toname)  
  16.         </div>  
  17.     </div>  
  18.     <div class="form-group">  
  19.         @Html.LabelFor(m => m.toemail, new { @class = "col-md-2 control-label" })  
  20.         <div class="col-md-10">  
  21.             @Html.TextBoxFor(m => m.toemail, new { @class = "form-control" })  
  22.             @Html.ValidationMessageFor(m => m.toemail)  
  23.         </div>  
  24.     </div>  
  25.     <div class="form-group">  
  26.         @Html.LabelFor(m => m.subject, new { @class = "col-md-2 control-label" })  
  27.         <div class="col-md-10">  
  28.             @Html.TextBoxFor(m => m.subject, new { @class = "form-control" })  
  29.             @Html.ValidationMessageFor(m => m.subject)  
  30.         </div>  
  31.     </div>  
  32.     <div class="form-group">  
  33.         @Html.LabelFor(m => m.message, new { @class = "col-md-2 control-label" })  
  34.         <div class="col-md-10">  
  35.             @Html.TextAreaFor(m => m.message, new { @class = "form-control" })  
  36.             @Html.ValidationMessageFor(m => m.message)  
  37.         </div>  
  38.     </div>  
  39.     <div class="form-group">  
  40.         <div class="col-md-offset-2 col-md-10">  
  41.             <input type="submit" class="btn btn-default" value="Send" />  
  42.         </div>  
  43.     </div>  
  44. }  
Step 6
 
Then, go to the HomeController and add the below code for Index Post method.
  1. [HttpPost]  
  2. [ValidateAntiForgeryToken]  
  3. public async Task<ActionResult> Index(EmailModel model)  
  4. {  
  5.     using (var client = new HttpClient())  
  6.     {  
  7.         //Passing service base url    
  8.         client.BaseAddress = new Uri(Baseurl);  
  9.   
  10.         client.DefaultRequestHeaders.Clear();  
  11.         //Define request data format    
  12.         client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  13.   
  14.         //Sending request to find web api REST service using HttpClient    
  15.         HttpResponseMessage Res = await client.PostAsJsonAsync("api/email/send-email", model);  
  16.   
  17.         //Checking the response is successful or not which is sent using HttpClient    
  18.         if (Res.IsSuccessStatusCode)  
  19.         {  
  20.             return View("Success");  
  21.         }  
  22.         else  
  23.         {  
  24.             return View("Error");  
  25.         }  
  26.     }  
  27. }  
Step 7
 
After that, create two new view pages - Success and Error. If the email is sent successfully, it will redirect to the Success page; otherwise, it redirects to the Error page. For that, add the below code to HomeController.
  1. public ActionResult Success()  
  2. {  
  3.     return View();  
  4. }  
  5.   
  6. public ActionResult Error()  
  7. {  
  8.     return View();  
  9. }  
Now, right-click on Success() and Error() and click on "Add View" like in the below images.
 
Send Email Using ASP.NET MVC And Web API
 
Send Email Using ASP.NET MVC And Web API
 
Step 8
 
Move to the Web.config file and add the below code. 
  1. <system.net>  
  2.     <mailSettings>  
  3.         <smtp from = "[email protected]" >  
  4.             <network host="smtp.gmail.com"   
  5.                     port="587"   
  6.                     userName="[email protected]"   
  7.                     password="yourmailpasswd"   
  8.                     enableSsl="true" />  
  9.         </smtp>  
  10.     </mailSettings>  
  11. </system.net>  
Here, we are using SMTP Class to send the email.
 
SMTP Class
 
Following are the properties of the SMTP class.
  • Host - SMTP Server URL (here we use smtp.gmail.com).
  • EnableSsl - Specify whether your host accepts SSL Connections.
  • Credentials - Valid login credentials for the SMTP server (userName: email address and password: email address password).
  • Port - Port number of the SMTP server (For Gmail: 587).
Step 9
 
Now, save and run your project. It will look like the below, in the browser.
 
Send Email Using ASP.NET MVC And Web API
 
Step 10
 
Fill the fields and click on the Send button. When the Send button is clicked, the posted values are captured through the EmailModel class object and set into an object of the MailMessage class to send an email. If the email is successfully sent then it will redirect to the success page.
 
If you will get an error from the GMAIL Server, then first, you must check whether the Username and Password supplied are correct. If your Username and Password are correct but still you get an error, check your "Allows less secure apps" option of the given email. If this option is off, then turn it on. To check "Allows less secure apps" setting, first, log in to your Gmail account then visit the below link.
 
Link - https://myaccount.google.com/lesssecureapps
 
Send Email Using ASP.NET MVC And Web API
 
I hope this is useful for all readers. Happy Coding!


Similar Articles