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:

<table style="height: 317px; width: 386px">

<tr>

    <td>

        Select File:

    </td>

    <td>

        <input type="file" id="MyFile" name="MyFile" />

    </td>

</tr>

<tr>

    <td>

        Subject:</td>

    <td>

        <asp:TextBox ID="TxtSubject" runat="server"></asp:TextBox>

    </td>

</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:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

<title>Untitled Document</title>

</head>

 

<body>

<table border="2">

<tr>

<td>Dear Member:</td>

<td>$$Member$$</td>

</tr>

<tr>

<td>Subject:</td>

<td>$$Subject$$</td>

</tr>

<tr>

<td colspan="2">

<img src="file:///C:/Users/njoshi/Downloads/Attachments_20131129/image001.jpg"></td>

</tr>

</table>

</body>

</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.

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

<asp:GridView ID="GridView1" runat="server" Height="205px" Width="356px" AutoGenerateColumns="False">

 

<Columns>

    <asp:TemplateField HeaderText="Operations">

        <ItemTemplate>

            <asp:Button ID="Button1" runat="server" CausesValidation="false" CommandName="SendMail" Text="Send" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>

        </ItemTemplate>

    </asp:TemplateField>

    <asp:TemplateField HeaderText="Name">

        <ItemTemplate>

        <asp:Label ID="LblName" runat="server" Text='<%# Eval("Name") %>'></asp:Label>

        </ItemTemplate>

    </asp:TemplateField>

    <asp:TemplateField HeaderText="EmailID">

       <ItemTemplate>

        <asp:Label ID="LblEmail" runat="server" Text='<%# Eval("Email_ID") %>'></asp:Label>

       </ItemTemplate>

    </asp:TemplateField>

</Columns>

</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:

    string MyFile, Mail, Name;

     

    if (e.CommandName == "SendMail")

    {

         HttpPostedFile PostedFile=Request.Files["MyFile"]; 

     

        if(PostedFile !=null && PostedFile.ContentLength>0 )

        {

     

            MyFile = Path.GetFileName(PostedFile.FileName);

            PostedFile.SaveAs(Server.MapPath(Path.Combine("~/UploadedFile/", MyFile)));

    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:

    int index=Convert.ToInt32(e.CommandArgument.ToString());

    Label LblName = GridView1.Rows[index].FindControl("LblName") as Label;

    Label LblMail = GridView1.Rows[index].FindControl("LblEmail") as Label;

    Name = LblName.Text;

    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:

StreamReader reader = new StreamReader(Server.MapPath(Path.Combine("~/UploadedFile/", MyFile)));

string readfile = reader.ReadToEnd();

string mystring = "";

mystring = readfile;

mystring = mystring.Replace("$$Member$$", Name);

mystring = mystring.Replace("$$Subject$$", TxtSubject.Text);

MailMessage Msg = new MailMessage();

MailAddress fromMail = new MailAddress(FromEmailid);

Msg.From = fromMail;

Msg.To.Add(new MailAddress(Mail));

Msg.Subject = TxtSubject.Text;

Msg.Body = mystring.ToString();

Msg.IsBodyHtml = true;

Entire Code:

The following is the entire code of the RowCommand event:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)

        {

            try

            {

                string Pass, FromEmailid, HostAdd;

                string MyFile, Mail, Name;

 

                if (e.CommandName == "SendMail")

                {

                    int index = Convert.ToInt32(e.CommandArgument.ToString());

                    Label LblName = GridView1.Rows[index].FindControl("LblName") as Label;

                    Label LblMail = GridView1.Rows[index].FindControl("LblEmail") as Label;

                    Name = LblName.Text;

                    Mail = LblMail.Text; 

 

                    HttpPostedFile PostedFile = Request.Files["MyFile"]; 

 

                    if (PostedFile != null && PostedFile.ContentLength > 0)

                    { 

                        HostAdd = ConfigurationManager.AppSettings["Host"].ToString();

                        FromEmailid = ConfigurationManager.AppSettings["FromMail"].ToString();

                        Pass = ConfigurationManager.AppSettings["Password"].ToString();

 

                        MyFile = Path.GetFileName(PostedFile.FileName);

                        PostedFile.SaveAs(Server.MapPath(Path.Combine("~/UploadedFile/", MyFile)));

 

                        StreamReader reader = new StreamReader(Server.MapPath(Path.Combine("~/UploadedFile/", MyFile)));

                        string readfile = reader.ReadToEnd();

                        string mystring = "";

                        mystring = readfile;

                        mystring = mystring.Replace("$$Member$$", Name);

                        mystring = mystring.Replace("$$Subject$$", TxtSubject.Text);

                        MailMessage Msg = new MailMessage();

 

                        MailAddress fromMail = new MailAddress(FromEmailid);

                        Msg.From = fromMail;

                        Msg.To.Add(new MailAddress(Mail));

                        Msg.Subject = TxtSubject.Text;

                        Msg.Body = mystring.ToString();

                        Msg.IsBodyHtml = true;

 

                        SmtpClient smtp = new SmtpClient();

                        smtp.Host = HostAdd;

                        smtp.EnableSsl = true;

                        NetworkCredential n = new NetworkCredential(FromEmailid, Pass);

                        smtp.UseDefaultCredentials = true;

                        smtp.Port = 587;

                        smtp.Credentials = n;

                        smtp.Send(Msg);

                        Label1.Text = "Send Successfully";

                        reader.Dispose();

                    }

 

                    else

                    {

                        Label1.Text = "No File is Selected.";

                    }

                }

            }

            catch (Exception ex)

            {

                Label1.Text = ex.Message;

            }

        }

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!!