C# 在电子邮件中发送表格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8811353/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Send a table in email
提问by 14578446
I have a requirement to send the results of a query in emails. I am using two methods:
我需要通过电子邮件发送查询结果。我正在使用两种方法:
GetDataTable(): to execute the query and obtain datatable(which needs to be sent in email)
GetDataTable():执行查询并获取数据表(需要通过电子邮件发送)
SendAutomatedEmail(): to send automated emails.
SendAutomatedEmail():发送自动电子邮件。
Problem: i need to send data table or html table in email, something like code below. this works fine for a string in place of dataTable
问题:我需要在电子邮件中发送数据表或 html 表,类似于下面的代码。这适用于代替 dataTable 的字符串
public static void Main(string[] args)
{
DataTable datatable = GetDataTable();
SendAutomatedEmail(datatable );
}
public static DataTable GetDataTable(string CommandText)
{
string cnString = ConfigurationManager.ConnectionStrings["Connection2"].ConnectionString;
SqlConnection sqlConnection = new SqlConnection(cnString);
string CommandText = "select * from dbo.fs010100 (nolock)";
SqlCommand sqlCommand = new SqlCommand( CommandText, sqlConnection);
SqlDataAdapter sqlDataAdapter = new System.Data.SqlClient.SqlDataAdapter();
sqlDataAdapter.SelectCommand = sqlCommand;
DataTable dataTable = new DataTable();
dataTable.Locale = System.Globalization.CultureInfo.InvariantCulture;
// Adds or refreshes rows in the DataSet to match those in the data source
try
{
sqlDataAdapter.Fill(dataTable);
sqlConnection.Close(dataTable );
}
catch (Exception _Exception)
{
sqlConnection.Close();
//Console.WriteLine(_Exception.Message);
return null;
}
return dataTable;
}
public static void SendAutomatedEmail(DataTable dt, string recipient = "[email protected]")
{
try
{
string mailServer = "server.com";
MailMessage message = new MailMessage(
"[email protected]",
recipient,
"Test Email",
dt.ToString()
);
SmtpClient client = new SmtpClient(mailServer);
var AuthenticationDetails = new NetworkCredential("[email protected]", "password");
client.Credentials = AuthenticationDetails;
client.Send(message);
}
catch (Exception e)
{
}
}
采纳答案by user1157131
ok, try this now:
好的,现在试试这个:
public static void Main(string[] args)
{
DataSet dataSet = getDataSet();
string htmlString= getHtml(dataSet);
SendAutomatedEmail(htmlString, "[email protected]");
}
public static DataSet getDataSet(string CommandText)
{
string cnString = ConfigurationManager.ConnectionStrings["Connection2"].ConnectionString;
SqlConnection sqlConnection = new SqlConnection(cnString);
string CommandText = "select * from dbo.fs010100 (nolock)";
SqlCommand sqlCommand = new SqlCommand( CommandText, sqlConnection);
SqlDataAdapter sqlDataAdapter = new System.Data.SqlClient.SqlDataAdapter();
sqlDataAdapter.SelectCommand = sqlCommand;
DataSet dataSet = new DataSet();
try
{
sqlDataAdapter.Fill(dataSet, "header");
sqlConnection.Close();
}
catch (Exception _Exception)
{
sqlConnection.Close();
return null;
}
return dataSet;
}
public static string getHtml(DataSet dataSet)
{
try
{
string messageBody = "<font>The following are the records: </font><br><br>";
if (dataSet.Tables[0].Rows.Count == 0)
return messageBody;
string htmlTableStart = "<table style=\"border-collapse:collapse; text-align:center;\" >";
string htmlTableEnd = "</table>";
string htmlHeaderRowStart = "<tr style =\"background-color:#6FA1D2; color:#ffffff;\">";
string htmlHeaderRowEnd = "</tr>";
string htmlTrStart = "<tr style =\"color:#555555;\">";
string htmlTrEnd = "</tr>";
string htmlTdStart = "<td style=\" border-color:#5c87b2; border-style:solid; border-width:thin; padding: 5px;\">";
string htmlTdEnd = "</td>";
messageBody+= htmlTableStart;
messageBody += htmlHeaderRowStart;
messageBody += htmlTdStart + "Column1 " + htmlTdEnd;
messageBody += htmlHeaderRowEnd;
foreach (DataRow Row in notShippedDataSet.Tables[0].Rows)
{
messageBody = messageBody + htmlTrStart;
messageBody = messageBody + htmlTdStart + Row["fieldName"] + htmlTdEnd;
messageBody = messageBody + htmlTrEnd;
}
messageBody = messageBody + htmlTableEnd;
return messageBody;
}
catch (Exception ex)
{
return null;
}
}
public static void SendAutomatedEmail(string htmlString, string recipient = "[email protected]")
{
try
{
string mailServer = "server.com";
MailMessage message = new MailMessage("[email protected]", recipient);
message .IsBodyHtml = true;
message .Body = htmlString;
message .Subject = "Test Email";
SmtpClient client = new SmtpClient(mailServer);
var AuthenticationDetails = new NetworkCredential("[email protected]", "password");
client.Credentials = AuthenticationDetails;
client.Send(message);
}
catch (Exception e)
{
}
}
回答by fiat
In the past, I've made an object EmailGrid.cs which inherits from GridView. Then used a method like below to render the HTML into a string.
过去,我创建了一个从 GridView 继承的对象 EmailGrid.cs。然后使用如下方法将 HTML 渲染为字符串。
public string RenderControl()
{
StringBuilder stringBuilder = new StringBuilder();
StringWriter stringWriter = new StringWriter(stringBuilder);
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
RenderControl(htmlTextWriter);
return stringBuilder.ToString();
}
回答by MethodMan
If you are wanting to do the same thing but loop thru the datatable via a DataAdapter look at this link for a quick example .. because you are pretty much doing the same thing this example shows with the exception you are trying to pass the entire datatable vs building the results into the email body.. How to use DataAdapter to DataTable via Email
如果您想做同样的事情,但通过 DataAdapter 循环遍历数据表,请查看此链接以获取快速示例.. vs 将结果构建到电子邮件正文中。 如何通过电子邮件使用 DataAdapter 到 DataTable
回答by Juan Canizález
Other dynamic function:
其他动态功能:
private string RenderDataTableToHtml(DataTable dtInfo)
{
StringBuilder tableStr = new StringBuilder();
if(dtInfo.Rows != null && dtInfo.Rows.Count > 0)
{
int columnsQty = dtInfo.Columns.Count;
int rowsQty = dtInfo.Rows.Count;
tableStr.Append("<TABLE BORDER=\"1\">");
tableStr.Append("<TR>");
for (int j = 0; j < columnsQty; j++)
{
tableStr.Append("<TH>" + dtInfo.Columns[j].ColumnName + "</TH>");
}
tableStr.Append("</TR>");
for (int i = 0; i < rowsQty; i++)
{
tableStr.Append("<TR>");
for (int k = 0; k < columnsQty; k++)
{
tableStr.Append("<TD>");
tableStr.Append(dtInfo.Rows[i][k].ToString());
tableStr.Append("</TD>");
}
tableStr.Append("</TR>");
}
tableStr.Append("</TABLE>");
}
return tableStr.ToString();
}
}

