Sending Emails In ASP.NET With Email Templates

In this article, you will learn the following things,

  • What are Email Templates?
  • How to send emails from an ASP.NET WebForm?
  • Step By Step Implementation of Sending Email By Email Templates in ASP.NET WebFom.

What are Email Templates?

Email templates is a predefined body of text of email messages. Sending email is just about filling in the blank fields.

Example

NewUserName is a blank field you'll replace with actual data like “Ashish / Suhana Kalla”.

Dear [NewUserName]  (this text in email templates)

Dear Ashish / Suhana Kalla (While sending system will replace the NewUserName with Actual User Name)

How to send email through Asp.Net WebForm?

We can send Email through coding that's codebehind. For this the following things are required :

  1. Email Account: In this article we had used GMAIL accounts.
  2. Email Account SMTP Detail.
  3. Code of Email Sending: In dot net framework there are two namespaces, System.Net, System.Net.Mail required.
    1. using System.Net;  
    2. using System.Net.Mail;   

System.Net namespace used for set NetworkCredential in below image you can see.

ASP.NET WebForm

System.Net.Mail namespace used for classes called “MailMessage” and “SMTP”

In image you can see MailMessage is dedicated to sending email messages using SMTP client.

ASP.NET WebForm

In image you can see detail of SmtpClient.

ASP.NET WebForm

Code Explanation

  • Base class for sending email
    MailMessage _mailmsg = new MailMessage();

  • Make TRUE because our body text is html
    _mailmsg.IsBodyHtml = true;

  • Set From Email ID
    _mailmsg.From = new MailAddress(emailSender);

  • Set To Email ID
    _mailmsg.To.Add(txtUserName.Text.ToString());

  • Set Subject
    _mailmsg.Subject = subject;

  • Set Body Text of Email
    _mailmsg.Body = MailText;

  • Now set your SMTP
    SmtpClient _smtp = new SmtpClient();

  • Set HOST server SMTP detail
    _smtp.Host = emailSenderHost;

  • Set PORT number of SMTP
    _smtp.Port = emailSenderPort;

  • Set SSL --> True / False
    _smtp.EnableSsl = emailIsSSL;     

  • Set Sender UserEmailID, Password
    NetworkCredential _network = new NetworkCredential(emailSender, emailSenderPassword);
    _smtp.Credentials = _network;

  • Send Method will send your MailMessage create above.
    _smtp.Send(_mailmsg);

As per best practice in this article the following things are fetched from Web.Config file:

  1. Sender Email ID
  2. Password
  3. SMTP server detail.
  4. Port Number
  5. IsSSL value.

For complete code you can see Signup.aspx.cs file. 

Step By Step Implementation of Sending Email By Email Templates in Asp.Net WebFom

For this task we go through the following 7 steps,

  1. Create Asp.Net Empty Web Site Project.
  2. Insert New HTML File named ”SignUp.html”
  3. Write the content for SignUp.html (Code of HTML)
  4. Free webmail Gmail / Yahoo account and SMTP Settings required.
  5. Config updation with SMTP setting.
  6. Insert a new WebForm file.
  7. Write code to shoot email using email template called Signup.html.

Now we go step by step as per the above points in a simple way, that's easier to learn.  

Start Visual Studio, I am using Visual Studio 2015 Community Edition.

STEP 1

Create a new Project by clicking on FILE --> WebSite

In below image you see I had used Asp.Net Empty Web Site

ASP.NET WebForm

STEP 2

Create a new folder called “EmailTemplates” you create a new folder by right click on project title in Solution explorer.

By right clicking you can see the below give image; select NEW FOLDER; after that one folder comes your project; rename it to “EmailTemplates”.

ASP.NET WebForm

After taking the above step your solution explorer looks like this,

ASP.NET WebForm

Now select EmailTemplates folder and insert a new HTML file inside folder. To insert a new HTML file you have to again right click on project and select Add New Item.

ASP.NET WebForm

Select HTML Page and give name “SignUp.html”.

ASP.NET WebForm

In SignUp.Html file we will set basic body text of email which shoots/executes while new user registers/signs up on portal/site.

In signup email we will send user’s User Name. 

Code in SignUp.html

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title></title>  
  5.     <meta charset="utf-8" />  
  6.     <style>  
  7.         table, th, td {  
  8.     border: 1px solid black;  
  9. }  
  10.     </style>  
  11. </head>  
  12. <body>  
  13.        <br />  
  14.     <table width="50%">  
  15.         <tr>  
  16.             <td align="center" style="background-color:yellow">  
  17.                 <span style="font-size:25px;">   Welcome To C# Corner  </span>  
  18.                 <br />  
  19.                 <br />  
  20.             </td>  
  21.               
  22.         </tr>  
  23.           
  24.         <tr align="center">  
  25.             <td>  
  26.                 <br />  
  27.                 <br />  
  28.                 Dear [newusername]  
  29.                 <br />  
  30.                 <br />  
  31.                Thank you for registering with us!  
  32.                 <br />  
  33.                 <a href="http://www.c-sharpcorner.com">  
  34.                     Click here to Login  
  35.                 </a>  
  36.   
  37.                 Regards,  
  38.                 <br />  
  39.                 <br />  
  40.             </td>  
  41.             </tr>  
  42. <tr>  
  43.             <td align="center" style="background-color:yellow">  
  44.                 <br />  
  45.                 <br />  
  46.                 <span style="font-size:15px;text-decoration:underline">   Share your knowledge   </span>  
  47.                 <br />  
  48.                 <span style="font-size:20px;">   <i>If you have knowledge, let others light their candles in it - Margaret Fuller    </span>  
  49.                 <br />  
  50.                 <br />  
  51.             </td>  
  52.   
  53.         </tr>  
  54.   
  55.     </tr>  
  56.           
  57.   
  58.     </table>  
  59. </body>  
  60. </html>  

Email Template Output looks like,

ASP.NET WebForm

STEP 3 Sending through Gmail Account

Email Account : <Your Gmail Account>
E.g.:  [email protected] 

Password:     <Your Gmail Account Password>

SMTP Detail:  smtp.gmail.com
(SMTP stand for Simple Mail Transfer Protocol)

Port Detail: 587

Note

If you want to send mail through shared hosting or other domains the above things are required.
 

STEP 4 - Updation of Web.Config file

As per best practice we should always store settings kind of things into Web.Config file.

Now we are going to store settings of gmail/yahoo account into web.config file.

Code in Web.Config file

  1. <?xml version="1.0"?>  
  2.   
  3. <!--  
  4.   For more information on how to configure your ASP.NET application, please visit  
  5.   http://go.microsoft.com/fwlink/?LinkId=169433  
  6.   -->  
  7.   
  8. <configuration>  
  9.   <appSettings>  
  10.     <add key="smtp" value="smtp.gmail.com"/>  
  11.     <add key="portnumber" value="587"/>  
  12.     <add key="username" value="[email protected]"/>  
  13.     <add key="password" value="abc@123"/>  
  14.     <add key="IsSSL" value="true"/>  
  15.   </appSettings>  
  16.   <system.web>  
  17.     <compilation debug="true" targetFramework="4.5.2" />  
  18.     <httpRuntime targetFramework="4.5.2" />  
  19.   </system.web>  
  20.   
  21. </configuration>  

STEP 5

To insert a new web form file you have to again right click on project and select Add New Item.

ASP.NET WebForm

Insert a new WebForm file named “Signup.aspx”

In signup.aspx there are only three(3) server side controls.

  1. TextBox used for USER NAME.
  2. TextBox used for PASSWORD.
  3. Button used for SUBMIT

Code in Signup.aspx file

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Signup.aspx.cs" Inherits="Signup" %>  
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title></title>  
  8.     <style type="text/css">  
  9.         .auto-style1 {  
  10.             height: 30px;  
  11.         }  
  12.     </style>  
  13. </head>  
  14. <body>  
  15.     <form id="form1" runat="server">  
  16.         <div>  
  17.             <h3>New User (Signup)</h3>  
  18.             <table>  
  19.                 <tr>  
  20.                     <td>User Name<br />  
  21.                         (Email ID)  
  22.                     </td>  
  23.                     <td>  
  24.                         <asp:TextBox ID="txtUserName" runat="server" Width="200px"></asp:TextBox>  
  25.                     </td>  
  26.                 </tr>  
  27.                 <tr>  
  28.                     <td>  
  29.                         <br />  
  30.                         Password  
  31.                     </td>  
  32.   
  33.                     <td>  
  34.                         <br />  
  35.                         <asp:TextBox ID="txtPassword" runat="server" TextMode="Password" Width="200px"> </asp:TextBox>  
  36.                     </td>  
  37.                 </tr>  
  38.                 <tr>  
  39.                     <td colspan="2" class="auto-style1">  
  40.                         <asp:Button ID="btnSubmit" runat="server" Text="Register (Signup)" OnClick="btnSubmit_Click" />  
  41.                     </td>  
  42.                 </tr>  
  43.             </table>  
  44.         </div>  
  45.     </form>  
  46. </body>  
  47. </html>  

Code in Signup.aspx.cs file

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7.   
  8. //System.Net  
  9. using System.Net;  
  10.   
  11. //System.Net.Mail namespace required to send mail.  
  12. using System.Net.Mail;  
  13.   
  14. using System.Configuration;  
  15. using System.IO;  
  16.   
  17. public partial class Signup : System.Web.UI.Page  
  18. {  
  19.     protected void Page_Load(object sender, EventArgs e)  
  20.     {  
  21.   
  22.     }  
  23.   
  24.     protected void btnSubmit_Click(object sender, EventArgs e)  
  25.     {  
  26.         //Fetching Settings from WEB.CONFIG file.  
  27.         string emailSender = ConfigurationManager.AppSettings["emailsender"].ToString();  
  28.         string emailSenderPassword = ConfigurationManager.AppSettings["password"].ToString();  
  29.         string emailSenderHost = ConfigurationManager.AppSettings["smtpserver"].ToString();  
  30.         int emailSenderPort = Convert.ToInt16(ConfigurationManager.AppSettings["portnumber"]);  
  31.         Boolean emailIsSSL = Convert.ToBoolean(ConfigurationManager.AppSettings["IsSSL"]);  
  32.   
  33.   
  34.         //Fetching Email Body Text from EmailTemplate File.  
  35.         string FilePath = "D:\\MBK\\SendEmailByEmailTemplate\\EmailTemplates\\SignUp.html";  
  36.         StreamReader str = new StreamReader(FilePath);  
  37.         string MailText = str.ReadToEnd();  
  38.         str.Close();  
  39.   
  40.         //Repalce [newusername] = signup user name   
  41.         MailText = MailText.Replace("[newusername]", txtUserName.Text.Trim());  
  42.                  
  43.   
  44.         string subject = "Welcome to CSharpCorner.Com";  
  45.   
  46.         //Base class for sending email  
  47.         MailMessage _mailmsg = new MailMessage();  
  48.   
  49.         //Make TRUE because our body text is html  
  50.         _mailmsg.IsBodyHtml = true;  
  51.   
  52.         //Set From Email ID  
  53.         _mailmsg.From = new MailAddress(emailSender);  
  54.   
  55.         //Set To Email ID  
  56.         _mailmsg.To.Add(txtUserName.Text.ToString());  
  57.   
  58.         //Set Subject  
  59.         _mailmsg.Subject = subject;  
  60.   
  61.         //Set Body Text of Email   
  62.         _mailmsg.Body = MailText;  
  63.   
  64.   
  65.         //Now set your SMTP   
  66.         SmtpClient _smtp = new SmtpClient();  
  67.   
  68.         //Set HOST server SMTP detail  
  69.         _smtp.Host = emailSenderHost;  
  70.   
  71.         //Set PORT number of SMTP  
  72.         _smtp.Port = emailSenderPort;  
  73.   
  74.         //Set SSL --> True / False  
  75.         _smtp.EnableSsl = emailIsSSL;  
  76.   
  77.         //Set Sender UserEmailID, Password  
  78.         NetworkCredential _network = new NetworkCredential(emailSender, emailSenderPassword);  
  79.         _smtp.Credentials = _network;  
  80.   
  81.         //Send Method will send your MailMessage create above.  
  82.         _smtp.Send(_mailmsg);  
  83.   
  84.   
  85.           
  86.     }  
  87. }  

Page Output

ASP.NET WebForm
After clicking on REGISTER(SIGNUP) welcome (SIgnup) )maill will goes to [email protected]

Yahoo.com account’s Mail Screen Shot - Mail reached at destination

ASP.NET WebForm

Enjoy and Happy Coding….


Similar Articles