【问题标题】:Send a table in email通过电子邮件发送表格
【发布时间】:2012-02-07 08:11:48
【问题描述】:

我需要通过电子邮件发送查询结果。我使用了两种方法:

GetDataTable() : 执行查询并获取数据表(需要通过电子邮件发送)

SendAutomatedEmail():发送自动电子邮件。

问题:我需要在电子邮件中发送数据表或 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 = "user@domain.com")
    {
        try
        {
            string mailServer = "server.com";

            MailMessage message = new MailMessage(
                                                   "it@domain.com",
                                                   recipient,
                                                   "Test Email",
                                                   dt.ToString()
                                                   );
            SmtpClient client = new SmtpClient(mailServer);
            var AuthenticationDetails = new NetworkCredential("user@domain.com", "password");
            client.Credentials = AuthenticationDetails;
            client.Send(message);
        }
        catch (Exception e)
        {

        }

    }

【问题讨论】:

  • 表格必须在邮件正文中吗?
  • 是的,email的内容就是表格
  • 你可以把建表的原始html写出来,放在邮件正文中,例如:
    header
    行数据
    。但请注意,许多电子邮件客户端都关闭了支持 HTML 的邮件,因此请确保不要破坏用户体验。
  • 记得设置message.IsBodyHTML=true。

标签: c# .net email data-binding html-email


【解决方案1】:

在正文消息中插入此代码:


public string GetHtmlTable(string title, DataTable table)
        {
            try
            {
                string messageBody = "<font> "+title+" </font><br><br>";

                if (table.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;
                
                foreach(DataColumn column in table.Columns)
                    messageBody += htmlTdStart + column + htmlTdEnd;

                messageBody += htmlHeaderRowEnd;

                foreach (DataRow row in table.Rows)
                {
                    messageBody +=  htmlTrStart;


                    foreach (string item in row.ItemArray)
                    {
                        messageBody += htmlTdStart;
                        messageBody += item;
                        messageBody += htmlTdEnd;
                    }
                    messageBody += htmlTrEnd;
                }
                messageBody += htmlTableEnd;


                return messageBody;
            }
            catch (Exception e)
            {
                return null;
            }
        }

【讨论】:

    【解决方案2】:

    其他动态功能:

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

    【讨论】:

      【解决方案3】:

      好的,现在试试这个:

      public static void Main(string[] args)
      {
          DataSet dataSet = getDataSet();
          string htmlString= getHtml(dataSet);
          SendAutomatedEmail(htmlString, "email@domain.com");
      }
      
      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 = "user@domain.com")
      
      {
       try
       {
           string mailServer = "server.com";
      
           MailMessage message = new MailMessage("it@domain.com", recipient);
           message .IsBodyHtml = true;
           message .Body = htmlString;
           message .Subject = "Test Email";
      
           SmtpClient client = new SmtpClient(mailServer);
           var AuthenticationDetails = new NetworkCredential("user@domain.com", "password");
           client.Credentials = AuthenticationDetails;
           client.Send(message);
       }
       catch (Exception e)
       {
      
       }
      
      }
      

      【讨论】:

      • 这会在哪里循环列?这是一张只有一列的表格吗?
      【解决方案4】:

      如果您想做同样的事情,但通过 DataAdapter 循环遍历数据表,请查看此链接以获取快速示例 .. 因为您所做的几乎与此示例显示的相同,只是您尝试传递的异常整个数据表与将结果构建到电子邮件正文中.. How to use DataAdapter to DataTable via Email

      【讨论】:

        【解决方案5】:

        过去,我创建了一个继承自 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();
                }
        

        【讨论】:

        • 我在控制台应用程序中执行此操作,没有 system.web.dll dere
        • 您是通过控制台应用程序还是 Web 应用程序发送电子邮件,您可以使用 System.Web.Mail 添加到代码顶部的 using;
        • 但我无法找到对 system.web dll 的引用
        猜你喜欢
        • 2013-01-20
        • 1970-01-01
        • 1970-01-01
        • 2020-12-15
        • 1970-01-01
        • 2017-04-18
        • 2015-10-26
        • 2018-08-18
        • 1970-01-01
        相关资源
        最近更新 更多