2012-01-10 43 views
5

Tengo un requisito para enviar los resultados de una consulta en correos electrónicos. Estoy utilizando dos métodos:Enviar una tabla en el correo electrónico

GetDataTable (): para ejecutar la consulta y obtener la tabla de datos (que tiene que ser enviado por correo electrónico)

SendAutomatedEmail(): enviar correos electrónicos automatizados.

Problema: necesito enviar la tabla de datos o la tabla html en el correo electrónico, algo así como el código a continuación. esto funciona bien para una cadena en lugar de 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) 
     { 

     } 

    } 
+0

¿la mesa tiene que estar en el cuerpo del correo electrónico? – AllenG

+0

sí, el contenido del correo electrónico es la tabla – 14578446

+0

Usted sólo puede escribir el html prima para la construcción de una mesa, y lo puso en el cuerpo del correo electrónico, por ejemplo .:

cabecera
datos de fila
. Sin embargo, tenga en cuenta que muchos clientes de correo electrónico tienen el correo habilitado para HTML desactivado, así que asegúrese de no romper la experiencia del usuario. –

Respuesta

10

bien, tratar esto ahora:

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) 
{ 

} 

} 
1

En el pasado, he hecho un EmailGrid.cs objeto que hereda de GridView. Luego usó un método como el siguiente para convertir el HTML en una cadena.

public string RenderControl() 
     { 
      StringBuilder stringBuilder = new StringBuilder(); 
      StringWriter stringWriter = new StringWriter(stringBuilder); 
      HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter); 
      RenderControl(htmlTextWriter); 

      return stringBuilder.ToString(); 
     } 
+0

estoy haciendo esto en la aplicación de consola, no tengo system.web.dll dere – 14578446

+0

¿Está enviando un correo electrónico a través de la aplicación de consola o la aplicación web de cualquier forma que pueda agregar al uso en la parte superior del código usando System.Web.Mail; – MethodMan

+0

pero no puedo encontrar la referencia a system.web dll – 14578446

0

Si estás interesado en hacer lo mismo, pero en bucle a través de la tabla de datos a través de una mirada del adaptador de datos en este enlace para obtener un ejemplo rápido .. porque están haciendo más o menos lo mismo que este ejemplo muestra que con la excepción están tratando de pasar toda la tabla de datos frente a la construcción de los resultados en el cuerpo del correo electrónico .. How to use DataAdapter to DataTable via Email

Cuestiones relacionadas