Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

display datatable in body of email in c#

Tags:

c#

I am trying to display datatable in body of email. I am converting the datatable in html tags using the below function

private static string getHTML(DataTable dt)

    {
        StringBuilder myBuilder = new StringBuilder();

        myBuilder.Append("<table border='1px' cellpadding='5' cellspacing='0' ");
        myBuilder.Append("style='border: solid 1px Silver; font-size: x-small;'>");

        myBuilder.Append("<tr align='left' valign='top'>");
        foreach (DataColumn myColumn in dt.Columns)
        {
            myBuilder.Append("<td align='left' valign='top'>");
            myBuilder.Append(myColumn.ColumnName);
            myBuilder.Append("</td>");
        }
        myBuilder.Append("</tr>");

        foreach (DataRow myRow in dt.Rows)
        {
            myBuilder.Append("<tr align='left' valign='top'>");
            foreach (DataColumn myColumn in dt.Columns)
            {
                myBuilder.Append("<td align='left' valign='top'>");
                myBuilder.Append(myRow[myColumn.ColumnName].ToString());
                myBuilder.Append("</td>");
            }
            myBuilder.Append("</tr>");
        }
        myBuilder.Append("</table>");

        return myBuilder.ToString();
    }

and providing the returned string to stringbuilder like below

StringBuilder sb = new StringBuilder(); 
                sb.AppendLine("Dear Responsible,"); 
                sb.AppendLine(""); 
                sb.AppendLine("Following items are added."); 
                sb.AppendLine(""); 
                sb.AppendLine(myBuilder.ToString())    //here I want the data to       display in table format
                sb.AppendLine("Many thanks in advance!");
                sb.AppendLine("");

but my mail is getting displayed like below

Dear Responsible,

Following items are added.

<table border='1px' cellpadding='5' cellspacing='0' style='border: solid 1px Silver; font-size: x-small;'><tr align='left' valign='top'><td align='left' valign='top'>INC_NUMBER</td><td align='left' valign='top'>SERVICE</td><td align='left' valign='top'>ASSIGNED_GROUP</td><td align='left' valign='top'>ASSIGNEE</td><td align='left' valign='top'>STATUS</td><td align='left' valign='top'>DUEHOURS</td></tr><tr align='left' valign='top'><td align='left' valign='top'>INC</td><td align='left' valign='top'>GSI</td><td align='left' valign='top'>L2</td><td align='left' valign='top'>Mahen A</td><td align='left' valign='top'>Pending</td><td align='left' valign='top'>4</td></tr></table>

Many thanks in advance! 

How can that be displayed in table format instead of string???

like image 652
user1415173 Avatar asked Dec 27 '22 06:12

user1415173


1 Answers

Make sure you set the IsBodyHtml property of MailMessage to true.

like image 161
Daniel Hilgarth Avatar answered Jan 10 '23 07:01

Daniel Hilgarth