asp.net c# converting data in a dataset into body of an email?

What’s the best way to go from a dataset to the body of an email?

I have a .net console app to send email notification based on results of a stored proc and wanted to know how best to go from SQL data to Email body?

html body with colors and fonts would be best but plain text is also fine.

thanks.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

How’s that:

  1. Reference System.Web (add using System.Web.UI.WebControls;)
  2. Instantiate DataGrid or GridView or whatever output you like
  3. Bind DataTable
  4. Render to string – use something like

    var buffer = new StringBuilder(); 
    var tw = new HtmlTextWriter(new StringWriter(buffer))) 
    datagrid.RenderControl(tw); 
    var emailbodyHtmlPart = buffer.ToString();
    
  5. Do this for every DataTable in DataSet
  6. Add results to html body of email

This is, of course, not tested, but should work in principle.

Solution 2

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();
    }

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply