Send a table in email

前端 未结 4 1227
一生所求
一生所求 2020-12-29 15:02

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(wh

4条回答
  •  萌比男神i
    2020-12-29 15:15

    ok, try this now:

    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 = "The following are the records: 

    "; if (dataSet.Tables[0].Rows.Count == 0) return messageBody; string htmlTableStart = ""; string htmlTableEnd = "
    "; string htmlHeaderRowStart = ""; string htmlHeaderRowEnd = ""; string htmlTrStart = ""; string htmlTrEnd = ""; string htmlTdStart = ""; string htmlTdEnd = ""; 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) { } }

提交回复
热议问题