Notifications to end-users are a very crucial need for interactive web development. Popular forms of notifications in web development are emails and SMS alerts. It is essentially a responsibility of the websites (that are maintaining end-user accounts) to notify end-users about various interactions happening with their accounts, simply, to feel more secure, more aware, and more in control of their accounts with third-party products.
In today's tutorial, I will demonstrate the method of sending SMTP email notification using ASP.NET MVC5 platform.

Prerequisites
Following are some prerequisites before you proceed any further in this tutorial:
- Knowledge about ASP.NET MVC5.
- Knowledge about HTML.
- Knowledge about Javascript.
- Knowledge about AJAX.
- Knowledge about CSS.
- Knowledge about Bootstrap.
- Knowledge about C# programming.
- Knowledge about C# LINQ.
- Knowledge about JQuery.
You can download the complete source code for this tutorial or you can follow the step by step discussion below. The sample code is developed in Microsoft Visual Studio 2015 Enterprise.
Let's begin now.Step 1
Create new MVC5 web application project and name it "EmailNotification".
Step 2
I like to keep my sensitive information into resource (.resx) files instead of web.config file. So, create a "Resources/Constants/EmailInfo.resx" resource (.resx) file and ensure that "Access Modifier" of the file is "Public" as shown below i.e.

Since I am going to use a Gmail account as a source email address for sending email notifications, hence, I will be using "smtp.gmail.com" as my host type configuration with port "587" which are essential configuration properties for SMTP protocol. You can use "587" port for other common email host types as well. Below are the list of host type configuration for other common email host types i.e.
- GMAIL SMTP HOST -> smtp.gmail.com
- YAHOO SMTP HOST -> smtp.mail.yahoo.com
- HOTMAIL/LIVE SMTP HOST -> smtp.live.com
- OUTLOOK/Exchange Server SMTP HOST -> smtp-mail.outlook.com
In order to send email notifications from your website to end-users of your web product, you need to have a source email account. The concept is simple here, you need an email account to send a notification to another email account. The only difference is that your source email account should not be your personal account, so, it cannot be misused. For example, when you receive email notifications from your social media accounts, notice that they specifically write "do-not-reply" in the name of the email address or mention that at the end of the email notifications that not to reply to this email address. The reason is simple -- they have fixed that particular email account for sending notifications only, according to the actions you perform on their websites. So, here below are the mandatory configuration properties within your code to configure your source email address for sending email notifications to the end-users i.e.:
- FROM_EMAIL_ACCOUNT
- FROM_EMAIL_PASSWORD
- SMTP_HOST_TYPE
- SMTP_PORT
Step 3
Create the following list of properties within the "Resources/Constants/EmailInfo.resx" resource (.resx) file as shown below, i.e.

Notice in the above that I have left "FROM_EMAIL_ACCOUNT" and "FROM_EMAIL_PASSWORD" configuration properties empty i.e.:

These are your source email account email addresses and passwords. You need to update that while executing this tutorial.
Step 4
Now, Open "Views\Shared\_Layout.cshtml" page and replace following code in it:
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>@ViewBag.Title</title>
- @Styles.Render("~/Content/css")
- @Scripts.Render("~/bundles/modernizr")
- <!-- Font Awesome -->
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />
- </head>
- <body>
- <div class="navbar navbar-inverse navbar-fixed-top">
- <div class="container">
- <div class="navbar-header">
- <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- </button>
- </div>
- </div>
- </div>
- <div class="container body-content">
- @RenderBody()
- <hr />
- <footer>
- <center>
- <p><strong>Copyright © @DateTime.Now.Year - <a href="http://wwww.asmak9.com/">Asma's Blog</a>.</strong> All rights reserved.</p>
- </center>
- </footer>
- </div>
- @*Scripts*@
- @Scripts.Render("~/bundles/jquery")
- @Scripts.Render("~/bundles/jqueryval")
- @Scripts.Render("~/bundles/bootstrap")
- <!-- Custom Form -->
- @Scripts.Render("~/scripts/custom-form")
- @RenderSection("scripts", required: false)
- </body>
- </html>
In the above code, I have simply created a basic layout design for the web pages and include necessary references to the require libraries.
Step 5
Now, create "Models\EmailNotifyViewModel.cs" file and replace following code in this file:
- //-----------------------------------------------------------------------
- // <copyright file="EmailNotifyViewModel.cs" company="None">
- // Copyright (c) Allow to distribute this code and utilize this code for personal or commercial purpose.
- // </copyright>
- // <author>Asma Khalid</author>
- //-----------------------------------------------------------------------
- namespace EmailNotification.Models
- {
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- /// <summary>
- /// Email notification view model class.
- /// </summary>
- public class EmailNotifyViewModel
- {
- #region Properties
- /// <summary>
- /// Gets or sets to email address.
- /// </summary>
- [Required]
- [Display(Name = "To (Email Address)")]
- public string ToEmail { get; set; }
- #endregion
- }
- }
In the above code, I have simply created my View Model to attach it with the corresponding UI.
Step 6
Now, create "Controllers\EmailNotifyController.cs.cs" file and replace following code in it:
- //-----------------------------------------------------------------------
- // <copyright file="EmailNotifyController.cs" company="None">
- // Copyright (c) Allow to distribute this code and utilize this code for personal or commercial purpose.
- // </copyright>
- // <author>Asma Khalid</author>
- //-----------------------------------------------------------------------
- namespace EmailNotification.Controllers
- {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using Models;
- using System.Threading.Tasks;
- using System.Net.Mail;
- using Resources.Constants;
- using System.Net;
- /// <summary>
- /// Email notification controller class.
- /// </summary>
- public class EmailNotifyController : Controller
- {
- #region Index view method.
- #region Get: /EmailNotify/Index method.
- /// <summary>
- /// Get: /EmailNotify/Index method.
- /// </summary>
- /// <returns>Return index view</returns>
- public ActionResult Index()
- {
- try
- {
- }
- catch (Exception ex)
- {
- // Info
- Console.Write(ex);
- }
- // Info.
- return this.View();
- }
- #endregion
- #region POST: /EmailNotify/Index
- /// <summary>
- /// POST: /EmailNotify/Index
- /// </summary>
- /// <param name="model">Model parameter</param>
- /// <returns>Return - Response information</returns>
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> Index(EmailNotifyViewModel model)
- {
- try
- {
- // Verification
- if (ModelState.IsValid)
- {
- // Initialization.
- string emailMsg = "Dear " + model.ToEmail + ", <br /><br /> Thist is test <b style='color: red'> Notification </b> <br /><br /> Thanks & Regards, <br />Asma Khalid";
- string emailSubject = EmailInfo.EMAIL_SUBJECT_DEFAUALT + " Test";
- // Sending Email.
- await this.SendEmailAsync(model.ToEmail, emailMsg, emailSubject);
- // Info.
- return this.Json(new { EnableSuccess = true, SuccessTitle = "Success", SuccessMsg = "Notification has been sent successfully! to '" + model.ToEmail + "' Check your email." });
- }
- }
- catch (Exception ex)
- {
- // Info
- Console.Write(ex);
- // Info
- return this.Json(new { EnableError = true, ErrorTitle = "Error", ErrorMsg = ex.Message });
- }
- // Info
- return this.Json(new { EnableError = true, ErrorTitle = "Error", ErrorMsg = "Something goes wrong, please try again later" });
- }
- #endregion
- #endregion
- #region Helper
- #region Send Email method.
- /// <summary>
- /// Send Email method.
- /// </summary>
- /// <param name="email">Email parameter</param>
- /// <param name="msg">Message parameter</param>
- /// <param name="subject">Subject parameter</param>
- /// <returns>Return await task</returns>
- public async Task<bool> SendEmailAsync(string email, string msg, string subject = "")
- {
- // Initialization.
- bool isSend = false;
- try
- {
- // Initialization.
- var body = msg;
- var message = new MailMessage();
- // Settings.
- message.To.Add(new MailAddress(email));
- message.From = new MailAddress(EmailInfo.FROM_EMAIL_ACCOUNT);
- message.Subject = !string.IsNullOrEmpty(subject) ? subject : EmailInfo.EMAIL_SUBJECT_DEFAUALT;
- message.Body = body;
- message.IsBodyHtml = true;
- using (var smtp = new SmtpClient())
- {
- // Settings.
- var credential = new NetworkCredential
- {
- UserName = EmailInfo.FROM_EMAIL_ACCOUNT,
- Password = EmailInfo.FROM_EMAIL_PASSWORD
- };
- // Settings.
- smtp.Credentials = credential;
- smtp.Host = EmailInfo.SMTP_HOST_GMAIL;
- smtp.Port = Convert.ToInt32(EmailInfo.SMTP_PORT_GMAIL);
- smtp.EnableSsl = true;
- // Sending
- await smtp.SendMailAsync(message);
- // Settings.
- isSend = true;
- }
- }
- catch (Exception ex)
- {
- // Info
- throw ex;
- }
- // info.
- return isSend;
- }
- #endregion
- #endregion
- }
- }






KAIN PEPEPosted Sep 25, 2018, 10:35 PM
Thanks, Great Article, keep it up!