Accessing the HTML Body as an Email Message Body

Introduction

This article explains how to attach the HTML file body as a body of an Email in an ASP.NET Web Application.

I am taking an Excel file as the data source of my application for displaying in the Grid View. You must read Connectivity to Excel to show the accessibility of the Excel file in ASP.NET. I am adding content to it.

Let's proceed with the following sections:

  • Uploading File
  • HTML File
  • Working with Grid View
  • Code Implementation
  • Email Body

Uploading File

At first we will use a file upload to upload an HTML file with the procedure given below.

Step 1: Open the WebForm of your Web Application

Step 2: Now, add the following code before your grid view:

  1. <table style="height: 317px; width: 386px">  
  2. <tr>  
  3.     <td>  
  4.         Select File:  
  5.     </td>  
  6.     <td>  
  7.         <input type="file" id="MyFile" name="MyFile" />  
  8.     </td>  
  9. </tr>  
  10. <tr>  
  11.     <td>  
  12.         Subject:</td>  
  13.     <td>  
  14.         <asp:TextBox ID="TxtSubject" runat="server"></asp:TextBox>  
  15.     </td>  
  16. </tr> 

The code above will create a File Upload and a TextBox to take the subject of the Email. Now we need to create a HTML file to upload. We can use any HTML file but we need to do some type of changes in it.

HTML File

Step 1: Open any HTML file

Step 2: Create some content as in the code provided below:

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />  
  5. <title>Untitled Document</title>  
  6. </head>  
  7. <body>  
  8. <table border="2">  
  9. <tr>  
  10. <td>Dear Member:</td>  
  11. <td>$$Member$$</td>  
  12. </tr>  
  13. <tr>  
  14. <td>Subject:</td>  
  15. <td>$$Subject$$</td>  
  16. </tr>  
  17. <tr>  
  18. <td colspan="2">  
  19. <img src="file:///C:/Users/njoshi/Downloads/Attachments_20131129/image001.jpg"></td>  
  20. </tr>  
  21. </table>  
  22. </body>  
  23. </html> 

Step 3: Save it your location with the extension of .html.

Working with Grid View

Now we need to change our Grid View and add some buttons in it with the following procedure.

Step 1: Add the following code of the Grid View in the next row of the table:

  1. <asp:GridView ID="GridView1" runat="server" Height="205px" Width="356px" AutoGenerateColumns="False">  
  2. <Columns>  
  3.     <asp:TemplateField HeaderText="Operations">  
  4.         <ItemTemplate>  
  5.             <asp:Button ID="Button1" runat="server" CausesValidation="false" CommandName="SendMail" Text="Send" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>  
  6.         </ItemTemplate>  
  7.     </asp:TemplateField>  
  8.     <asp:TemplateField HeaderText="Name">  
  9.         <ItemTemplate>  
  10.         <asp:Label ID="LblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>  
  11.         </ItemTemplate>  
  12.     </asp:TemplateField>  
  13.     <asp:TemplateField HeaderText="EmailID">  
  14.        <ItemTemplate>  
  15.         <asp:Label ID="LblEmail" runat="server" Text='<%# Eval("Email_ID") %>'></asp:Label>  
  16.        </ItemTemplate>  
  17.     </asp:TemplateField>  
  18. </Columns>  
  19. </asp:GridView> 

I changed the fields into the Template Field for getting the column values easily.

Note: Please note that the Value of AutoGenerateColumns must be false, otherwise the source table may be displayed in the browser more then once.

Step 2: Let's check out the WebForm by debugging the application:

Home Page

Code Implementation

Now, we have completed the designing part of our application and so let's proceed the code implementation with the procedure given below.

Step 1: Open the Grid View properties as shown below:

Properties of Grid View

Step 2: Just double-click on the RowCommand event to generate its event.

Row Command in Grid View

Step 3: Open the WebForm Code view to write the code in the Grid View Row Command. We need to use the fileupload code in it. So, let us pproceed to understand it by the following points.

  • Create a folder

    At first we need to create a folder in the application for saving the HTML file uploaded by file upload

    Adding Folder in Web Application
     
  • File Upload

    Now, we need to check determine whether the file was uploaded successfully. Paste the following code into the RowCommand Event of the Grid View:
    1. string MyFile, Mail, Name;  
    2. if (e.CommandName == "SendMail")  
    3. {  
    4.     HttpPostedFile PostedFile=Request.Files["MyFile"];   
    5.     if(PostedFile !=null && PostedFile.ContentLength>0 )  
    6.     {  
    7.         MyFile = Path.GetFileName(PostedFile.FileName);  
    8.         PostedFile.SaveAs(Server.MapPath(Path.Combine("~/UploadedFile/", MyFile)));  
    9.     }  

    With the code above we will check that the file is present or not. If present then it will be saved into the UploadedFile Folder.

  • Sender Name and Email

    Now we need to store the name and email of that row in which we are sending the mail. Add the following code before file upload code:
    1. int index=Convert.ToInt32(e.CommandArgument.ToString());  
    2. Label LblName = GridView1.Rows[index].FindControl("LblName"as Label;  
    3. Label LblMail = GridView1.Rows[index].FindControl("LblEmail"as Label;  
    4. Name = LblName.Text;  
    5. Mail = LblMail.Text;  

     

          Using the code above we can store the Receiver's Name and Mail ID.

Email Body

Now after checking the file in the file upload and storing the name and email of the receiver, we need to create code for taking the HTML body as an Email body. Paste the following code after the "Postedfile.SaveAs" method:

 

  1. StreamReader reader = new StreamReader(Server.MapPath(Path.Combine("~/UploadedFile/", MyFile)));  
  2. string readfile = reader.ReadToEnd();  
  3. string mystring = "";  
  4. mystring = readfile;  
  5. mystring = mystring.Replace("$$Member$$", Name);  
  6. mystring = mystring.Replace("$$Subject$$", TxtSubject.Text);  
  7. MailMessage Msg = new MailMessage();  
  8. MailAddress fromMail = new MailAddress(FromEmailid);  
  9. Msg.From = fromMail;  
  10. Msg.To.Add(new MailAddress(Mail));  
  11. Msg.Subject = TxtSubject.Text;  
  12. Msg.Body = mystring.ToString();  
  13. Msg.IsBodyHtml = true;  

 

Entire Code:

The following is the entire code of the RowCommand event:

  1. protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)  
  2. {  
  3.     try  
  4.     {  
  5.         string Pass, FromEmailid, HostAdd;  
  6.         string MyFile, Mail, Name;  
  7.         if (e.CommandName == "SendMail")  
  8.         {  
  9.             int index = Convert.ToInt32(e.CommandArgument.ToString());  
  10.             Label LblName = GridView1.Rows[index].FindControl("LblName"as Label;  
  11.             Label LblMail = GridView1.Rows[index].FindControl("LblEmail"as Label;  
  12.             Name = LblName.Text;  
  13.             Mail = LblMail.Text;   
  14.             HttpPostedFile PostedFile = Request.Files["MyFile"];   
  15.             if (PostedFile != null && PostedFile.ContentLength > 0)  
  16.             {   
  17.                 HostAdd = ConfigurationManager.AppSettings["Host"].ToString();  
  18.                 FromEmailid = ConfigurationManager.AppSettings["FromMail"].ToString();  
  19.                 Pass = ConfigurationManager.AppSettings["Password"].ToString();  
  20.                 MyFile = Path.GetFileName(PostedFile.FileName);
                    PostedFile.SaveAs(Server.MapPath(Path.Combine("~/UploadedFile/", MyFile)));  
  21.                 StreamReader reader = new StreamReader(Server.MapPath(Path.Combine("~/UploadedFile/", MyFile)));  
  22.                 string readfile = reader.ReadToEnd();  
  23.                 string mystring = "";  
  24.                 mystring = readfile;  
  25.                 mystring = mystring.Replace("$$Member$$", Name);  
  26.                 mystring = mystring.Replace("$$Subject$$", TxtSubject.Text);  
  27.                 MailMessage Msg = new MailMessage();  
  28.                 MailAddress fromMail = new MailAddress(FromEmailid);  
  29.                 Msg.From = fromMail;  
  30.                 Msg.To.Add(new MailAddress(Mail));  
  31.                 Msg.Subject = TxtSubject.Text;  
  32.                 Msg.Body = mystring.ToString();  
  33.                 Msg.IsBodyHtml = true;  
  34.                 SmtpClient smtp = new SmtpClient();  
  35.                 smtp.Host = HostAdd;  
  36.                 smtp.EnableSsl = true;  
  37.                 NetworkCredential n = new NetworkCredential(FromEmailid, Pass);  
  38.                 smtp.UseDefaultCredentials = true;  
  39.                 smtp.Port = 587;  
  40.                 smtp.Credentials = n;  
  41.                 smtp.Send(Msg);  
  42.                 Label1.Text = "Send Successfully";  
  43.                 reader.Dispose();  
  44.             }  
  45.             else  
  46.             {  
  47.                 Label1.Text = "No File is Selected.";  
  48.             }  
  49.         }  
  50.     }  
  51.     catch (Exception ex)  
  52.     {  
  53.         Label1.Text = ex.Message;  
  54.     }  
  55. }

Debugging and Checking the Email Body:

Step 1: Debug the application

Sending File

Step 2: Now at the Mail Body, we can check the HTML Body attached as an Email Body. Insert a breakpoint on rowcommand and check out the mail body:

Text Visualizer

Step 3: Proceed to email.

Summary

With this article you can send a HTML file body as an Email body to any person. You can also select the file without using the FileUpload tool in an ASP.NET Web Application. So, go for it and let me know if you have any problem. Thanks for reading, Happy Coding!!


Similar Articles