8
votes

Envoyer une table dans l'email

J'ai besoin d'envoyer les résultats d'une requête dans des emails. J'utilise deux méthodes:

getdatatable () : Pour exécuter la requête et obtenir de la clé (qui doit être envoyé dans l'e-mail)

SENDAUTOMADEMAIL () < / Strong>: Pour envoyer des courriels automatisés.

Problème: Je dois envoyer une table de données ou une table HTML dans le courrier électronique, quelque chose comme le code ci-dessous. Cela fonctionne bien pour une chaîne à la place de DataTable xxx


4 commentaires

La table doit-elle être dans le corps de l'email?


Oui, le contenu de l'email est la table


Vous pouvez simplement écrire le code HTML brut pour la construction d'une table et le mettre dans le corps de l'e-mail, par exemple:

Header
Données de ligne < / td> . Notez cependant, de nombreux clients de messagerie disposent d'un courrier activé HTML désactivé, alors assurez-vous de ne pas casser l'expérience utilisateur.


N'oubliez pas de définir le message.isbodyhtml = true.


5 Réponses :


1
votes

Dans le passé, j'ai fait un objet EmailGrid.cs qui hérite de GridView. Puis utilisé une méthode comme ci-dessous pour rendre le HTML dans une chaîne.

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

            return stringBuilder.ToString();
        }


3 commentaires

Je fais cela dans la demande de console, ne pas avoir system.web.dll dere


Envoyez-vous des emails via une application de console ou une application Web de toute façon, vous pouvez ajouter à l'utilisation en haut du code à l'aide de System.Web.Mail;


mais je ne suis pas capable de trouver référence à system.web dll



0
votes

Si vous voulez faire la même chose, mais la boucle à travers le jeu via un datadapter examine ce lien pour un exemple rapide .. Parce que vous faites à peu près la même chose que cet exemple montre avec l'exception que vous essayez de passer L'ensemble des fichiers de données vs construisez les résultats dans l'organisme email .. Comment utiliser DataDapter vers DataTable par e-mail < / a>


0 commentaires

18
votes

OK, essayez ceci maintenant:

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

 }

}


1 commentaires

Où est-ce que cette boucle les colonnes? Est-ce une table avec une seule colonne?



0
votes

Autre fonction dynamique: xxx


0 commentaires

0
votes

Insérer dans le message du corps Ce code:

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


0 commentaires